[MyBatis] 如何让MyBatis支持代码级事务处理
MyBatis提供的sqlSession对象是可以用来帮助我们实现事务处理的,方式和JDBC的类似,具体请见代码:
import java.sql.Connection; import java.sql.SQLException; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import jp.co.rakuten.rtms.batch.common.exception.BatchApplicationException; /** * To verify the possibility of commit/rollback after a part of code * @author Heyang * @date 19.10.04 */ @Component public class SweepawayExpiredDataInDB_TestRollback2 extends AbstractJob implements Job { /** SQL実行クラス */ @Autowired private SqlSession session; @Override public void doExecute(String[] args) { logger.info("SweepawayExpiredDataInDB_TestRollback started."); long startTime = System.currentTimeMillis(); try { logger.info("isAutoCommit="+session.getConnection().getAutoCommit()); Connection conn = session.getConnection(); conn.setAutoCommit(false); // 1 try { for(int i=0;i<10;i++) { Map<String, String> para=new HashMap<String, String>(); para.put("id",String.valueOf(i)); para.put("name","Andy"+i); session.insert("insertEmp", para); } conn.commit(); logger.info("1.Committed"); } catch (Exception e) { conn.rollback(); logger.info("1.Rollbacked"); e.printStackTrace(); } // 2 try { for(int i=0;i<10;i++) { Map<String, String> para=new HashMap<String, String>(); para.put("id",String.valueOf(i)); para.put("name","Andy"+i); session.insert("insertEmp", para); } conn.commit(); logger.info("2.Committed"); } catch (Exception e) { conn.rollback(); logger.info("2.Rollbacked"); e.printStackTrace(); } // 3 try { for(int i=0;i<10;i++) { Map<String, String> para=new HashMap<String, String>(); para.put("id",String.valueOf(100+i)); para.put("name","Cindy"+i); session.insert("insertEmp", para); } conn.rollback(); logger.info("3.Rollback mannualy"); } catch (Exception e) { conn.rollback(); logger.info("2.Rollbacked"); e.printStackTrace(); } //conn.commit(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{
session.close();
} long endTime = System.currentTimeMillis(); double seconds=((double)endTime - (double)startTime)/1000; logger.info("Time elapsed:" + seconds + "s"); logger.info("SweepawayExpiredDataInDB_TestRollback completed."); } }
--END-- 19.10.04 11:12