我有这种测试方法:
public void myMethod()
{
transactionManager.begin();
entityManager.joinTransaction();
MyEntity e = MyEntity();
entityManager.persist(e);
entityManager.flush();
Assert.assertNotNull(e);
Assert.assertNotNull(e.getId());
Long id = e.getId();
entityManager.detach(e);
Assert.assertFalse(entityManager.contains(e));
Assert.assertFalse(entityManager.getEntityManagerFactory().getCache().
contains(MyEntity.class, id));
e = null;
entityManager.getEntityManagerFactory().getCache().evictAll();
transactionManager.rollback();
entityManager.clear();
e = entityManager.find(MyEntity.class, id);
Assert.assertNull(e);
}
在相关的DB中没有任何MyEntity(每次运行测试时都会创建数据库),因为没有显式提交,DB在执行方法后保持清洁但是最后一个Assert(一个在最后一次查找之后)仍然继续失败,因为找到了先前的持久(但回滚)实例。
这是我的persistence.xml文件:
<persistence 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_2_0.xsd"
version="2.0">
<persistence-unit transaction-type="JTA" name="persistenceUnit">
<jar-file>myjar.jar</jar-file>
<properties>
<!-- validate | update | create | create-drop -->
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.validator.apply_to_ddl" value="false"/>
<property name="hibernate.id.new_generator_mappings" value="true"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:persistenceUnitDB"/>
<!--<property name="hibernate.connection.url" value="jdbc:hsqldb:file:persistenceUnitDB/persistenceUnitDB"/>-->
<property name="hibernate.connection.autocommit" value="false"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.BTMTransactionManagerLookup"/>
</properties>
</persistence-unit>
</persistence>
我无法理解为什么这段代码有这种行为。