spring事物的管理方式

本文来自:IT宝库(https://www.itbaoku.cn)

Spring事务配置的五种方式

转载大神总结:

https://blog.csdn.net/xuanjiewu/article/details/51604967;

自己总结:这里只总结spring编程时事物管理

附上源码加注释

两个方法放到一个类中,直接写你的逻辑调用即可。

/**
* jdbc批量处理插入操作
* @param list
* @return
*/
public int setOneExtractSetTwoTemplate(List<TwoQuotation> list){
List<List<Object>> listListTwo = new ArrayList<List<Object>>();
String sqlTwo ="";
List<List<Object>> listList = new ArrayList<List<Object>>();
for (int i = 0; i < list.size(); i++) {
List<Object> list1 = new ArrayList<Object>();
list1.add(list.get(i).getProjId());
.............
listList.add(list1);
}

String sql ="INSERT INTO DOC_SXJJHDXM_PBJL_repeated (docid,zbcs, bdh, bdname,"+
"tbdwname,wzbm,product, ggxh,"+
"jldw, dwnum, zzdj, wzth, ysccj, ppxh, chandi, taxes, tjsx, gys_uuid,"+
" wz_uuid,"+
"remark, repeate, address, starttime, endtime )"+
"VALUES"+
"(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

String flag = collectiveTransaction(listList, sql, listListTwo, sqlTwo);
if(flag.equals("yes")){
return 1;//代表成功
}
return 0;//0代表失败
}

/*parms
*
* 批量操作数据*/
@SuppressWarnings("unchecked")
public String collectiveTransaction(final List<List<Object>> listList,String sql,final List<List<Object>> listListTwo,
String sqlTwo) {

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);//事务的隔离级别,开启新事物
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);//获得事务的状态
String flag = "yes";
try{

if(listListTwo.size()>0){
jdbcTemplate.execute(sqlTwo, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
for (List<Object> list : listListTwo) {
for (int i = 0; i < list.size(); i++) {
ps.setString(i+1, (String) list.get(i));
}
ps.addBatch();
}
ps.executeBatch(); // 数据不会持久化到数据库中
return null ;
}
});
}

if(listList.size()>0){
jdbcTemplate.execute(sql, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
for (List<Object> list : listList) {
for (int i = 0; i < list.size(); i++) {
ps.setString(i+1, (String) list.get(i));
}
ps.addBatch();
}
ps.executeBatch(); // 数据不会持久化到数据库中
return null ;
}
});
}
transactionManager.commit(status); // 持久化所有数据

}catch (Exception e){
transactionManager.rollback(status); // 所有的数据都会rollback
e.printStackTrace();
flag = "no";
}
return flag;
}