title: DbUnit fails to clean-insert: foreign key constraint
body: <p>I'm asking and answering this question for future reference, because I think I've found a decent solution to a common problem with DbUnit. I hope it helps out someone, somewhere down the line.</p>
  
  <p>I'm using <code>DbUnit 2.5.0</code> and <code>TestNG 6.8.8</code>. My use case is for a part of a database which comprises 3 entities. There is a <code>ServiceUser</code> which holds a foreign key to both an <code>Administrable</code> and a <code>UserGroup</code>.</p>
  
  <p>I followed most of the code example from <a href="http://city81.blogspot.com/2011/03/testing-jpa-entities-using-dbunit.html">http://city81.blogspot.com/2011/03/testing-jpa-entities-using-dbunit.html</a></p>
  
  <pre><code>public abstract class AbstractDatabaseTest {
      protected EntityManager em; // initialized elsewhere
      private IDatabaseConnection connection;
      private IDataSet dataset;
  
      @BeforeClass
      private void setupDatabaseResource() throws Exception {
          // using Hibernate
          connection = new DatabaseConnection(((SessionImpl) (em.getDelegate())).connection());
          connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());
  
          // full database export
          IDataSet fullDataSet = connection.createDataSet();
  
          final String datasetPath = String.format("%s%s", RESOURCE_FOLDER, "Testing.xml");
          FlatXmlDataSet.write(fullDataSet, new FileOutputStream(datasetPath));
  
          FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder();
          flatXmlDataSetBuilder.setColumnSensing(true);
          dataset = flatXmlDataSetBuilder.build(new FileInputStream(datasetPath));
      }
  
      @AfterMethod
      public void cleanDB() throws Exception {
          em.getTransaction().begin();
          DatabaseOperation.CLEAN_INSERT.execute(connection, dataset);
          em.getTransaction().commit();
      }
  }
  </code></pre>
  
  <p>The result of this is the following <code>XMLDataSet</code> (data omitted):</p>
  
  <pre><code>&lt;dataset&gt;
    &lt;administrable/&gt;
    &lt;serviceuser/&gt;
    &lt;usergroup/&gt;
  &lt;/dataset&gt;
  </code></pre>
  
  <p>When <code>TestNG</code> executes the <code>@AfterMethod</code>, I get the following Exception:</p>
  
  <pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
  Cannot delete or update a parent row: a foreign key constraint fails (`testing_db`.`serviceuser`, CONSTRAINT `FK_gyylcfbhpl2ukqs5rm7sq0uy8` FOREIGN KEY (`userGroup_id`) REFERENCES `usergroup` (`id`))
  </code></pre>