2014-10-07 134 views
2

我有很多持續行的數據庫的方法,它是這樣的:數據庫沒有更新後的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個對象後提交,然後事務再次打開,依此類推。這個過程將重複,直到所有的對象都被持久化。

問題是,如果我中斷了執行,即使事務已經被提交,它也不會保存任何東西,只有在整個列表被處理後,對象纔會被保存在數據庫中。

有沒有人有任何想法我做錯了什麼?

+0

應該工作。我已經測試過你的代碼,並在每次提交之後查看數據庫中的記錄.... – 2014-10-07 22:20:01

+0

這就是日誌的用途,不是嗎? – 2014-10-08 07:32:30

+0

@AlanHay我剛剛用persistence.xml代碼和entityManager官方化更新了帖子。 – 2014-10-08 11:40:51

回答

-1

而不是提交,調用flush();做一些像

// open the transaction 
// start the loop 
// for each 500 call entityManager.flush(); 
// when the loop finishes, call commit() and finish the entityManagfer 
+0

爲什麼投了票?有時候人們沒有勇氣說出答案不好的原因...... -_-'' – uaiHebert 2014-10-07 23:24:04

+0

感謝您的回答!我明天會測試它。 – 2014-10-07 23:41:25

+1

Commit將寫入任何未刷新的更改,以便對flush()進行顯式調用不會產生任何影響:http://docs.oracle.com/javaee/6/api/javax/persistence/EntityTransaction.html#commit() – 2014-10-08 09:02:49