2016-04-20 47 views
0

我有4個對象,我不想爲每個對象使用session.save(obj)。有沒有辦法將所有對象保存在循環中或同時保存。休眠用一個會話保存許多不同的對象.save

對於一個循環,我將不得不增加變量名稱,但我認爲這是不可能的或解決問題的「好方法」。

final Test a1 = new Test(6,"AA", 50, 100000,"20.04.2016","AAA", 111, "2016", "EEE"); 
    final Test a2 = new Test(7,"AB", 1050, 200000,"20.04.2016","BBB", 333, "2016", "EEE"); 
    final Test a3 = new Test(8,"AC", 40, 300000,"20.04.2016","CCC", 222, "2016", "UUU", "YY", 5, "SSS"); 
    final Test a4 = new Test(9,"PD", 400, 400000,"20.04.2016","DDD", 444, "2016", "CCC", "YY", 12, "RRR"); 

    session.beginTransaction(); 
    session.save(a1); 
    session.save(a2); 
    session.save(a3); 
    session.save(a4); 

    session.getTransaction().commit() 
+0

* 「我有4個對象,我不希望使用session.save(OBJ)爲每個對象。」 *爲什麼不完全?提供上下文可以讓人們瞭解您正在尋找什麼樣的解決方案。 – Gimby

回答

1

請使用數組

Test[] tests = new Test[] {new Test(), new Test()}; 

for(Test test : tests) { 
    session.save(test); 
} 
1

請閱讀批量處理,應該對您有用。

http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch15.html

例如:

Session session = sessionFactory.openSession(); 
Transaction tx = session.beginTransaction(); 

for (int i=0; i<100000; i++) { 
    Customer customer = new Customer(.....); 
    session.save(customer); 
    if (i % 20 == 0) { //20, same as the JDBC batch size 
     //flush a batch of inserts and release memory: 
     session.flush(); 
     session.clear(); 
    } 
} 

tx.commit(); 
session.close();