我有很多持續行的數據庫的方法,它是這樣的:數據庫沒有更新後的commit()
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個對象後提交,然後事務再次打開,依此類推。這個過程將重複,直到所有的對象都被持久化。
問題是,如果我中斷了執行,即使事務已經被提交,它也不會保存任何東西,只有在整個列表被處理後,對象纔會被保存在數據庫中。
有沒有人有任何想法我做錯了什麼?
應該工作。我已經測試過你的代碼,並在每次提交之後查看數據庫中的記錄.... – 2014-10-07 22:20:01
這就是日誌的用途,不是嗎? – 2014-10-08 07:32:30
@AlanHay我剛剛用persistence.xml代碼和entityManager官方化更新了帖子。 – 2014-10-08 11:40:51