Java 在DBUnit中重置序列?

Java 在DBUnit中重置序列?,java,dbunit,Java,Dbunit,我想在Java+DBUnit/中的每个测试之后重置数据库和序列 我见过这个问题,但没有我正在努力得到的代码解决方案。 如果下面的链接对您有帮助,请检查一下 我找到了答案,答案就在地图上。这就像在准备数据库时使用的数据集中一样简单,添加一个带有要重置序列列表的reset\u sequences属性 <?xml version='1.0' encoding='UTF-8'?> <dataset reset_sequences="emp_seq, dept_seq">

我想在Java+DBUnit/中的每个测试之后重置数据库和序列

我见过这个问题,但没有我正在努力得到的代码解决方案。

如果下面的链接对您有帮助,请检查一下


我找到了答案,答案就在地图上。这就像在准备数据库时使用的数据集中一样简单,添加一个带有要重置序列列表的reset\u sequences属性

 <?xml version='1.0' encoding='UTF-8'?>
    <dataset reset_sequences="emp_seq, dept_seq">
        <emp empno="1" ename="Scott" deptno="10" job="project manager" />
        ....
    </dataset>

我已经测试了@Chexpir提供的解决方案,这里有一种改进的/更干净的方法(PostgreSQL实现)-还要注意,序列被重置为1(而不是检索行计数)

在数据库TestCase中:

public abstract class AbstractDBTestCase extends DataSourceBasedDBTestCase {

    @Override
    protected DatabaseOperation getTearDownOperation() throws Exception {
        return new ResetSequenceOperationDecorator(DatabaseOperation.DELETE_ALL);
    }
}

您使用的是什么数据库?我是多数据库,所以我必须支持Oracle、Posgres和Derby。谢谢,但是使用CLEAN_INSERT对我没有帮助,我给出的答案是好的:-)
public class ResetSequenceOperationDecorator extends DatabaseOperation {

    private DatabaseOperation decoree;

    public ResetSequenceOperationDecorator(DatabaseOperation decoree) {
         this.decoree = decoree;
     }

     @Override
     public void execute(IDatabaseConnection connection, IDataSet dataSet) throws DatabaseUnitException, SQLException {
         String[] tables = dataSet.getTableNames();
         Statement statement = connection.getConnection().createStatement();
         for (String table : tables) {
             try {
                 statement.execute("ALTER SEQUENCE " + table + "_id_seq RESTART WITH 1");
             }
             // Don't care because the sequence does not appear to exist (but catch it silently)
             catch(SQLException ex) {
             }
         }
         decoree.execute(connection, dataSet);
     }
}
public abstract class AbstractDBTestCase extends DataSourceBasedDBTestCase {

    @Override
    protected DatabaseOperation getTearDownOperation() throws Exception {
        return new ResetSequenceOperationDecorator(DatabaseOperation.DELETE_ALL);
    }
}