讨论:Hibernate中成批插入或更新数据,设置每多少条时就写入数据库,并释放内存出来

05-05-27 YuLimin
讨论:Hibernate中成批插入或更新数据,设置每多少条时就写入数据库,并释放内存出来

/**

* 成批插入或更新数据,默认20条时就写入数据库,并释放内存出来

*

* @param list List

* @return boolean

* @throws HibernateException

*/

public boolean saveOrUpdateBatch(List list) throws HibernateException

{

return saveOrUpdateBatch(list,20);

}

/**

* 成批插入或更新数据,设置每多少条时就写入数据库,并释放内存出来

*

* @param list List

* @param iBatch int

* @throws HibernateException

* @return boolean

*/

public boolean saveOrUpdateBatch(List list,int iBatch) throws HibernateException

{

boolean isSuccess = false;

Transaction tx = null;

int i = 0;

try

{

tx = session.beginTransaction();

for(Iterator it = list.iterator();it.hasNext();)

{

session.saveOrUpdate(it.next()); //saveOrUpdate

i++;

if(i % iBatch == 0)

{

session.flush();

session.clear();

}

}

tx.commit();

logger.info("tx.wasCommitted:" + tx.wasCommitted());

isSuccess = true;

}

catch(HibernateException ex)

{

if(tx != null)

{

tx.rollback();

}

logger.info("tx.wasRolledBack:" + tx.wasRolledBack());

ex.printStackTrace();

throw ex;

}

finally

{

if(tx != null)

{

tx = null;

}

}

return isSuccess;

}

猜你喜欢