Resolve foreign key constraint error/conflict with DBUnit CLEAN_INSERT operation (MySQLIntegrityConstraintViolationException)

If DBUnit starts throwing MySQLIntegrityConstraintViolationException while performing a CLEAN_INSERT you can lose quite a bit of sleep attempting to resolve it or you can cheat and get back to work. The shortcut is to simply disable constraints for the INSERT operation by disabling constraints for DBUnit altogether. You can do that by adding sessionVariables=FOREIGN_KEY_CHECKS=0 to your JDBC connection string to MySQL. I use maven and in pom.xml my configuration for the dbunit plugin looks like this

<groupId>org.codehaus.mojo</groupId><artifactId>dbunit-maven-plugin</artifactId><version>1.0-beta-1</version><configuration>    <dataTypeFactoryName>${dbunit.dataTypeFactoryName}</dataTypeFactoryName>    <driver>${jdbc.driverClassName}</driver>    <username>${jdbc.username}</username>    <password>${jdbc.password}</password>    <url>${jdbc.url}&amp;sessionVariables=FOREIGN_KEY_CHECKS=0</url>    <src>src/test/resources/sample-data.xml</src>    <type>${dbunit.operation.type}</type>    <schema>${dbunit.schema}</schema>    <skip>${maven.test.skip}</skip></configuration>

Keep in mind that if you choose to do this your dbunit tests will run with constraints disabled....generally not a recommended approach. Caveat Emptor.

Share Comments