代码参考重明鸟 http://www.blogjava.net/allen-zhe/archive/2007/01/11/93207.html
主要代码如下:
/**
* 测试成批插入数据的事务处理,返回是否成功
*
* @param objPO
* Object
* @return boolean
*/
public void insertBatch(final List<Product> productList) {
Transaction transaction = null;
Session session = getSession();
try {
transaction = session.beginTransaction();
int i = 0;
for (Product p : productList) {
i++;
session.saveOrUpdate(p);
if (i % 50 == 0) {
// flush a batch of inserts and release memory
session.flush();
session.clear();
}
}
session.flush();
session.clear();
transaction.commit();
} catch (HibernateException ex) {
if (transaction != null) {
try {
transaction.rollback();
} catch (HibernateException ex1) {
ex1.printStackTrace();
}
}
ex.printStackTrace();
} finally {
if (transaction != null) {
transaction = null;
}
session.close();
}
}
该方法会产生一个异常,需要捕获,暂时无法解释原因。