Tuesday, 15 May 2012

Getting DBUnit to play nice with Hibernate hbm2ddl.auto database changes by extending DBTestCase

It is quite possible for DBUnit to try to populate your test database before hibernate has chance to validate,create or update it.  This is a problem if you are at an early stage with a system and are using Hibernate to create your database.

My solution is to extend DBTestCase to make sure it spins up a hibernate session the first time DBUnit is used.  

Note that I close the session so if you are using create-drop I dont think this will help as is.

Also note that this code will not run as-is since it includes the code for running an additional setup step . This takes a single DBUnit xml file and runs it to delete the data in the database.  The reason for this is that DBUnit gets its knickers in a twist with the table orders when deleting tables with foreign keys, this table allows you to specify a different delete structure. See this post.

No comments: