Import test and static data using Hibernate’s hibernate.hbm2ddl.auto

Hibernate comes with a nifty feature that makes it unnecessary to use DBUnit or any tool for initializing your test database with data before the unit and integration tests are run. Ofcourse you need to be using Hibernate Core or its JPA module to take advantage of this. Steps to achieve this are very straightforward

1. Configure Hibernate’s hibernate.hbm2ddl.auto property in the persistence.xml to one of the allowed values. e.g. The following configuration tells Hibernate to create the tables as per the given JPA/Hibernate mapping

<property name=”hibernate.hbm2ddl.auto” value=”create”/>

2. Place additional tables/sequences/trigger creation scripts and the test data insert statements in a file with name import.sql and place it in the runtime class path. In case of eclipse, put it directly under build/classes.

3. Make sure the insert statement has no newline character

That’s it!!

YM

This entry was posted in yourmitra and tagged , , . Bookmark the permalink.

One Response to Import test and static data using Hibernate’s hibernate.hbm2ddl.auto

  1. Will Tardy says:

    Hi, Database tables are created successfully by


    in persistence.xml, however each time I run my application (within Eclipse Helios), the import.sql doesn’t appear to be loading. My persistence.xml file

    org.hibernate.ejb.HibernatePersistence

    With the contents of import.sql I have tried removing line breaks, with+without semi colons “;”, tested the SQL on the command line (the insert statements work), tried intentionally broken SQL (produces no errors on console). I have tried placing import.sql at the root of my classpath, and also in META-INF (still no luck). I have tried putting “USE svrmonitor4;” at the start of the import.sql file (again, no luck).

    Am I missing something in persistence.xml?

    If errors were encountered upon inserting to the MySQL database, where are the errors reported? Eclipse console, or MySQL logs? I haven’t looked at MySQL logs yet.

    In Eclipse I have three projects, with dependencies as follows:

    Project A (contains Main class from which the app is launched) –> Project B –> Project C (contains Entity classes, persistence.xml)

    I have tried placing import.sql in the classpath of each of these projects, but it makes no difference.

    Can you please suggest some things I try to look at to get this working?

    (I’m running Hibernate 3.6.1, JPA2, MySQL 5.5.10, Eclipse Helios, Jboss Tools 3.4)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s