我有一个在数据库上保留大量行的方法,它是这样的:
private EntityManager em;
@PostConstruct
public void init() {
Map props = new HashMap();
props.put(PersistenceUnitProperties.JTA_DATASOURCE, dataSource());
EntityManagerFactory emf = Persistence.createEntityManagerFactory("db1", props);
em = emf.createEntityManager();
}
public void persistAll(List list) {
int count = 0;
for (Object o : list) {
if (count == 0) {
em.getTransaction().begin();
}
em.persist(o);
count++;
if (count >= 500) {
em.getTransaction().commit();
count = 0;
}
}
if (count > 0) {
em.getTransaction().commit();
}
}
这是我的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="db1" transaction-type="JTA">
<jta-data-source>db1</jta-data-source>
<mapping-file>orm.xml</mapping-file>
<class>com.entities.entity1</class>
<class>com.entities.entity2</class>
<class>com.entities.entity3</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="eclipselink.cache.size.default" value="0"/>
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
事务在开始时打开并在持久化500个对象后提交,然后再次打开事务,依此类推。此过程将重复,直到所有对象都保持不变。
问题是只有在处理完整个列表后才将对象保存在数据库中,如果我中断执行,即使事务已经提交,也不会保存任何内容。
有没有人知道我做错了什么?
答案 0 :(得分:-1)
而不是commit,调用flush();做点什么
// open the transaction
// start the loop
// for each 500 call entityManager.flush();
// when the loop finishes, call commit() and finish the entityManagfer