public void batchSave(Listlist) { Session session = P2MServiceLocator.getSessionFactory().openSession(); Transaction ts = session.beginTransaction(); for (int i = 0; i < list.size(); i++) { session.save(list.get(i)); if ((i % list.size()) == 0) { // 批次向数据库中提交,i % list.size()) == 1000,则每1000条向数据库新增 session.flush(); // 清空缓存区,释放内存供下批数据使用 session.clear(); } } ts.commit(); session.close(); }
private void batchSaveObject(final String objectId, final String creatorName, final String creatorId, final String[] taskId, final String[] taskName) { Session session = P2MServiceLocator.getSessionFactory().openSession(); Transaction ts = session.beginTransaction(); for (int i = 0; i < taskId.length; i++) { DataApprovalObject da = new DataApprovalObject(); da.setDataId(taskId[i]); da.setObjectId(objectId); da.setDataName(taskName[i]); da.setCreator(creatorName); da.setCreatorId(creatorId); da.setCreateTime(new Timestamp(new Date().getTime())); session.save(da); if ((i % taskId.length) == 0) { // 批次向数据库中提交,此值应与配置的批量尺寸一致 session.flush(); // 清空缓存区,释放内存供下批数据使用 session.clear(); } } ts.commit(); session.close(); }
private void batchSaveDATA(final String objectId, final String creatorName, final String creatorId, final String[] taskId, final String[] taskName) { Session session = P2MServiceLocator.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection conn) throws SQLException { String sql = " INSERT INTO PM_DATA_APPROVAL (ID,DATA_ID,OBJECT_ID,DATA_NAME,CREATOR,CREATEOR_ID,CREATE_TIME)" + " values (?,?,?,?,?,?,?) "; PreparedStatement ps = conn.prepareStatement(sql); for (int i = 0; i < taskId.length; i++) { ps.setString(1, CommonUtil.getUUID()); ps.setString(2, taskId[i]); ps.setString(3, objectId); ps.setString(4, taskName[i]); ps.setString(5, creatorName); ps.setString(6, creatorId); ps.setTimestamp(7, new Timestamp(new Date().getTime())); ps.addBatch(); } ps.executeBatch(); } }); tx.commit(); session.close(); }