Search code examples
javasqlspringdbunitspring-test

How to do a custom database setup/teardown in Spring Test Dbunit?


I would like to know how to create custom setups/teardown mostly to fix cyclyc refence issues where I can insert custom SQL commands with Spring Test Dbunit http://springtestdbunit.github.io/spring-test-dbunit/index.html.

Is there an annotation I can use or how can this be customized?


Solution

  • There isn't currently an annotation that you can use but you might be able to create a subclass of DbUnitTestExecutionListener and add custom logic in the beforeTestMethod. Alternatively you might get away with creating your own TestExecutionListener and just ordering it before DbUnitTestExecutionListener.

    Another, potentially better solution would be to re-design your database to remove the cycle. You could probably drop the reference from company to company_config and add a unique index to company_id in the company_config table:

    +------------+ 1 0..1 +--------------------------------+ | company |<---------| company_config | +------------+ +--------------------------------+ | company_id | | config_id | | ... | | company_id (fk, notnull, uniq) | +------------+ +--------------------------------+

    Rather than looking at company.config_id to get the config you would do select * from company_config where company_id = :id.