Hibernate - 未创建H2数据库

时间:2017-02-16 16:31:20

标签: java hibernate h2

我想将HibernateH2一起使用,我希望自动创建架构。网上有很多例子,我的配置似乎很好,但是没有创建。以前我用它MySQL并没有任何问题。是否有其他参数可以包含在H2的任何位置?

我的持久性单元在persistence.xml中定义如下:

<persistence-unit name="some.jpa.name"
    transaction-type="RESOURCE_LOCAL">

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <!-- tried with and without class property
    <class>some.package.KeywordTask</class>     
    -->
    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:h2:./test" />
        <property name="javax.persistence.jdbc.user" value="" />
        <property name="javax.persistence.jdbc.password" value="" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.hbm2ddl.auto" value="create" />
        <property name="show_sql" value="true" />
    </properties>

</persistence-unit>

由于show_sql设置为true,我希望看到create语句,但没有任何反应,即没有创建模式。

我将EntityManagerFactory保留为final static变量:

public static EntityManagerFactory emf = Persistence.createEntityManagerFactory("some.jpa.name");

在我的代码中的某个地方,我试图坚持一个实体:

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
KeywordTask task = new KeywordTask();
task.setKeyword(keywordTask.getKey());
task.setLimit(keywordTask.getValue());
em.persist(task);
em.getTransaction().commit();
em.close();

这会抛出异常,原因是:

org.h2.jdbc.JdbcSQLException: Table "KEYWORDTASK" not found;

由于未创建架构,因此是预期的。

如何创建架构?

1 个答案:

答案 0 :(得分:1)

这个问题的原因是无关紧要的!我在这里写的是为了防止其他人也面对它,花半天时间做这么愚蠢的事情。

首先,我从H2更改为Derby进行检查,然后才有效。通过这种方式,我确信persistence.xml配置没有问题。

在搜索日志之后,我意识到hibernate无法创建表,因为KeywordTask实体的一个属性是limit,它是一个保留字! (还记得我持久保存实例并观察setter名称的地方:setLimit。)更改属性名称后,它就可以了。