我使用DbUnit框架对我的JPA实体bean进行单元测试。我已从DB表生成实体。并且还将DB数据导出到xb文件中,DbUnit可以在执行测试时使用这些文件。
但是对于每次测试我都收到错误:
Caused by: org.hsqldb.HsqlException: integrity constraint violation: unique constraint or index violation; UK_25T4P9GXGVRCC8R3VL93JKAJE table: NEW_TAB
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.Constraint.getException(Unknown Source)
at org.hsqldb.index.IndexAVLMemory.insert(Unknown Source)
at org.hsqldb.persist.RowStoreAVL.indexRow(Unknown Source)
at org.hsqldb.TransactionManager2PL.addInsertAction(Unknown Source)
at org.hsqldb.Session.addInsertAction(Unknown Source)
at org.hsqldb.Table.insertSingleRow(Unknown Source)
at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
at org.hsqldb.StatementInsert.getResult(Unknown Source)
at org.hsqldb.StatementDMQL.execute(Unknown Source)
at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
我的测试persistence.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.dummy.entity.NewTab</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:UNITTEST"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
每个测试用例都使用:
执行try {
final DatabaseConnection connection = new DatabaseConnection(jdbcConnection);
//connection.getConnection().prepareStatement("SET DATABASE REFERENTIAL INTEGRITY FALSE").execute();
final DatabaseConfig config = connection.getConfig();
// config.setProperty(FEATURE_QUALIFIED_TABLE_NAMES, true);
config.setProperty(PROPERTY_ESCAPE_PATTERN, "\"?\"");
config.setProperty(PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());
final List<IDataSet> dataSets = getDataSets();
if (dataSets != null) {
for (IDataSet dataSet : dataSets) {
dbOperation.execute(connection, dataSet);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
对于多个实体的每个测试,我都会收到此错误。所以我觉得我的配置出了问题。如果您有任何想法,请告诉我。
答案 0 :(得分:1)
我通过删除每个JPA实体字段的@Column注释的attribure unique = true来解决此问题。不确定为什么DBUnit不理解该JPA enity有一个复合键。
删除unique = true,不会影响我,因为我没有在DB上进行任何创建/更新/取消事务。我只执行读取操作。