views:

37

answers:

2

My unit tests use Hibernate to connect to an in-memory HSQLDB database. I was hoping there would be a way to clear and recreate the database (the entire database including the schema and all the data) in JUnit's TestCase.setUp() method.

+2  A: 

you can config your hibernate configuration file to force database to recreate your tables and schema every time.

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>

hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g. validate | update | create | create-drop

if you don't like to have this config in your real hibernate config, you can create one hibernate config for unit testing purpose.

mohammad shamsi
+1  A: 
hibernate.hbm2ddl.auto=create-drop

And bootstrap a new SessionFactory.

Bozho