MyBatis第四讲:MyBatis事务管理

六、MyBatis事务管理

事务(Transaction),一般是指要做的或所做的事情。在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元。

<environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/>dataSource>
environment>

在MyBatis核心配置文件中,配置数据源时,可以通过transactionManager设置事务管理,Mybatis默认为手动提交事务,即手动调用事务处理方法

6、1MyBatis实现事务提交

当对数据进行增删改操作或对以整体业务数据操作后,可以使用SqlSession的commit方法实现事务提交

//提交事务
sqlSession.commit();

6、2MyBatis实现事务回滚

当对数据进行增删改操作或对以整体业务数据操作后,可以使用SqlSession的commit方法实现事务回滚

//回滚事务
sqlSession.rollback();

6、3MyBatis实现事务自动提交

public class MybatisUtil {//创建SqlSessionFactory工厂对象private static SqlSessionFactory sqlSessionFactory;static {try {//获取MyBatis核心配置文件数据源String resource = "mybatis-config.xml";//加载MyBatis核心配置文件InputStream inputStream = Resources.getResourceAsStream(resource);//通过SqlSessionFactoryBuilder的build方法创建SqlSessionFactory工厂对象sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}catch (Exception e){e.printStackTrace();}}//创建获取SqlSession对象方法public static SqlSession getSqlSession(){//设置MyBatis事务自动提交sqlSessionFactory.openSession(true);return sqlSessionFactory.openSession();}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部