java jpa sao.save事务提交过长优化
在项目中发现使用jpa的save方法一次插入数据超过一定数据,会导致事务提交时间过长,从而影响性能,经过查找资料和研究,发现使用jdbc,通过拼接sql的方法,只提交一次数据库请求,速度会提升很多,废话不多说,直接上代码。
/**
* 批量新增
* @param XXXX
* @see
* */
public void batchSave(final List<XXXX> XXXXList) {
StringBuffer sqlBuffer = new StringBuffer("INSERT INTO XXXX ");
sqlBuffer.append(" (EDIT_HISTORY_ID, MP_CUSTOMER, EDIT_MP_ID, MP_ID, CUSTOMER_ID, DATA_STATUS, AUDIT_STATUS ");
sqlBuffer.append(" , ARCHIVE_BASE_DATE, BIZ_ORG_CODE, CREATED_BY, CREATION_DATE, LAST_UPDATED_BY, LAST_UPDATE_DATE ");
sqlBuffer.append(" , RECORD_VERSION, DELETED_FLAG, DELETED_BY, DELETION_DATE, MP_IS_QUERY) ");
sqlBuffer.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
jdbcTemplate.batchUpdate(sqlBuffer.toString(), new BatchPreparedStatementSetter() {
String acountId = KmLoginAccount.getInstance().getAccountId();
String orgCode = KmLoginAccount.getInstance().getBizOrgCode();
/**
* 得到数量
* @return
* @see org.springframework.jdbc.core.BatchPreparedStatementSetter#getBatchSize()
*/
public int getBatchSize() {
return XXXXList.size();
}
/**
* 设置值
* @param ps
* @param i
* @throws SQLException
* @see org.springframework.jdbc.core.BatchPreparedStatementSetter#setValues(java.sql.PreparedStatement, int)
*/
@Override
public void setValues(PreparedStatement ps, int i)throws SQLException {
MpCustomerEdit cip = XXXXList.get(i);
ps.setString(1, cip.getEditHistoryId());
ps.setString(2, cip.getMpCustomer());
ps.setString(3, cip.getEditMpId());
ps.setString(4, cip.getMpId());
ps.setString(5, cip.getCustomerId());
ps.setString(6, cip.getDataStatus() != null ? cip.getDataStatus() : "0");
ps.setString(7, cip.getAuditStatus());
ps.setDate(8, new Date(new java.util.Date().getTime()));
ps.setString(9, orgCode);
ps.setString(10, cip.getCreatedBy() != null ? cip.getCreatedBy() : acountId);
ps.setDate(11, cip.getCreationDate() != null ? new Date(cip.getCreationDate().getTime()) : new Date(new java.util.Date().getTime()));
ps.setString(12, cip.getLastUpdatedBy() != null ? cip.getLastUpdatedBy() : acountId);
ps.setDate(13,cip.getLastUpdateDate() != null ? new Date(cip.getLastUpdateDate().getTime()) : new Date(new java.util.Date().getTime()));
ps.setDouble(14,0);
ps.setString(15, "0");
ps.setString(16, cip.getDeletedBy());
ps.setDate(17, new Date(new java.util.Date().getTime()));
ps.setString(18, cip.getMpIsQuery());
}
});
}