使用Hibernate 3.5进行批量插入

时间:2012-10-19 05:46:41

标签: hibernate spring-batch

如何使用hibernate 3.5

执行以下操作
INSERT INTO Table (Column1, Column2 ) VALUES
(Value1, Value2), (Value1, Value2)

2 个答案:

答案 0 :(得分:1)

您可能需要考虑使用无状态会话。但是,要小心,因为返回的结果(此实例中的客户)已分离。

http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/batch.html#batch-statelesssession

StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();

ScrollableResults customers = session.getNamedQuery("GetCustomers")
    .scroll(ScrollMode.FORWARD_ONLY);
while ( customers.next() ) {
    Customer customer = (Customer) customers.get(0);
    customer.updateStuff(...);
    session.update(customer);
}

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

答案 1 :(得分:0)

以下链接可以为您提供解决方案。

http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/batch.html

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

String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ...";
int createdEntities = s.createQuery( hqlInsert )
        .executeUpdate();
tx.commit();
session.close();