我有4个对象,我不想对每个对象使用session.save(obj)。有没有办法在循环中或一次保存所有对象。
对于一个循环,我将不得不增加变量名称,但我认为这不可能或者是解决问题的“好方法”。
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 :(得分:1)
请使用数组
Test[] tests = new Test[] {new Test(), new Test()};
for(Test test : tests) {
session.save(test);
}
答案 1 :(得分: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();