在我的应用程序的单元测试中,我想使用HSQLDB测试持久层。但是,这需要我显式提交事务对象。在其中一个测试中,这不会使foo实例持久化:
final Foo foo = new Foo("someValue");
final EntityManagerFactory factory = Persistence.createEntityManagerFactory("TestDataModel");
final EntityManager em = factory.createEntityManager();
em.persist(foo);
相反,每次我想要持久化和实体时,我必须启动并提交一个事务:
final Foo foo = new Foo("someValue");
final EntityManagerFactory factory = Persistence.createEntityManagerFactory("TestDataModel");
final EntityManager em = factory.createEntityManager();
final EntityTransaction et = em.getTransaction();
et.begin();
em.persist(foo);
et.commit();
在我的应用程序中,我没有使用任何@Transactional注释。我最终想要测试的类是jax-rs应用程序中的无状态服务(使用Needle注入EntityManager),这不需要我在存储实体时开始和提交事务。网络上的一些人说这个问题与hsqldb中的延迟写入有关,但是我已经将它添加到连接URL而没有产生任何差异。我还在Hibernate配置文件中启用了自动提交,并将刷新模式设置为always。
的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 name="TestDataModel" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Foo</class>
<properties>
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:db/db;shutdown=true;hsqldb.write_delay_millis=0;hsqldb.write_delay=false;" />
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.flushMode" value="ALWAYS" />
<property name="hibernate.connection.autocommit" value="true" />
</properties>
</persistence-unit>
</persistence>