1

I want to use Hibernate with H2 and I want the schema to be created automatically. There are many examples online and my configurations seem fine, but it is not created. Previously I used it with MySQL and did not have any problem. Are there additional parameters to be included in anywhere for H2?

My persistence unit is defined in persistence.xml as follows:

<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>

Since show_sql is set to true, I expect to see create statements but nothing happens, i.e. the schema is not created.

I keep my EntityManagerFactory as a final static variable:

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

In some place in my code, I am trying to persist an entity:

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();

This throws exception with cause:

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

which is expected since the schema is not created.

How can I get the schema created?

ram
  • 1,099
  • 1
  • 7
  • 22

1 Answers1

1

The reason of this problem was quite unrelated! I am writing it here in case some other guys might face it too, and spend half a day for such a stupid thing.

First, I changed from H2 to Derby to check, and it worked. In this way, I was sure that there was no problem with persistence.xml configuration.

After searching around the logs, I realized that hibernate was not able to create the table since one of the properties of the KeywordTask entity was limit, and it is a reserved word! (Remember the place that I persist an instance and observe the name of the setter: setLimit.) After changing the name of the property, it worked.

ram
  • 1,099
  • 1
  • 7
  • 22