ibatis 对事务和批量提交的处理,以及回滚的处理

时间:2022-08-15 21:41:23
//ibatis batch 示例
    protected void batchCreate(final List<T> memberList, final String statement) {
        
        SqlMapClientCallback callback = new SqlMapClientCallback() {
            public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {    
                executor.startBatch();
                for (T tObject : memberList) {               
                    executor.insert(statement, tObject); // statement在*MapSql.xml一条语句的id    
                }            
                executor.executeBatch();           
                return null;
                
            }
            
        };
        
如果有很多非查询的(insert/update/delete)语句要处理,为了减少网络通讯的流量,可以进行批处理
sqlMap.startBatch();
  insert/update/delete 语句处理
sqlMap.endBatch();

try {
      sqlMapClient.startTransaction(); 
//事务开始
      Person p = 
       (Person)sqlMapClient.queryForObject
                       ("getPerson", new Integer(9));

      p.setLastName("Smith");
      sqlMapClient.update("updatePerson", p);

      Department d = 
       (Department)sqlMapClient.queryForObject       
                       ("getDept", new Integer(3));

      p.setDepartment(d);
      sqlMapClient.update("updatePersonDept", p);

      sqlMapClient.commitTransaction(); 
//提交事务,从开始到这里是一个事务

} finally {
        sqlMapClient.endTransaction();
 //事务结束
}

//回滚

sqlMap.getCurrentConnection().rolback();

即可。