com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Cannot truncate a table referenced in a foreign key constraint (`cub_test`.`api_month_stat`, CONSTRAINT `api_month_stat_access` FOREIGN KEY (`id_api_access`) REFERENCES `cub_test`.`api_access` (`id_api_access`)) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:734) at com.mchange.v2.c3p0.impl.NewProxyStatement.execute(NewProxyStatement.java:1006) at org.dbunit.database.statement.SimpleStatement.executeBatch(SimpleStatement.java:66) at org.dbunit.operation.DeleteAllOperation.execute(DeleteAllOperation.java:122) at org.dbunit.operation.TruncateTableOperation.execute(TruncateTableOperation.java:84) at org.dbunit.AbstractDatabaseTester.executeOperation(AbstractDatabaseTester.java:179) at org.dbunit.AbstractDatabaseTester.onTearDown(AbstractDatabaseTester.java:82) at org.dbunit.DatabaseTestCase.tearDown(DatabaseTestCase.java:146)
When I tried to perform manually tear down operation truncate on table following problem appears:
mysql> truncate table api_access; ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (`cub_test`.`api_month_stat`, CONSTRAINT `api_month_stat_access` FOREIGN KEY (`id_api_access`) REFERENCES `cub_test`.`api_access` (`id_api_access`)) mysql>Problem is closely described at http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html. In our case was solution to use "DELETE_ALL" as tear down operation. Tear down operation define what happen when test is executed. It could loo like:
@Override protected DatabaseOperation getTearDownOperation() throws Exception { return DatabaseOperation.DELETE_ALL; }