mybatic与spring结合的事务管理

mybatic与spring结合的事务管理

原文地址:http://czj4451.iteye.com/blog/2037759

mybatis与spring结合后,事务管理更加方便,这里介绍使用transactionnal的方式,有错的的地方,希望大家指出。

1. 和Spring集成后,使用Spring的事务管理:

a. @Transactional方式:

在类路径下创建beans-da-tx.xml文件,在applicationContext-resources.xml的基础上加入事务配置:

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

服务类:

@Service("userService")

publicclass UserService {

@Autowired

IUserMapper mapper;

publicint batchUpdateUsersWhenException() {// 非事务性

User user =new User(9,"Before exception");

int affectedCount = mapper.updateUser(user);// 执行成功

User user2 =new User(10,"After exception");

int i =1 /0;// 抛出运行时异常

int affectedCount2 = mapper.updateUser(user2);// 未执行

if (affectedCount ==1 && affectedCount2 ==1) {

return1;

}

return0;

}

@Transactional

publicint txUpdateUsersWhenException() {// 事务性

User user =new User(9,"Before exception");

int affectedCount = mapper.updateUser(user);// 因后面的异常而回滚

User user2 =new User(10,"After exception");

int i =1 /0;// 抛出运行时异常,事务回滚

int affectedCount2 = mapper.updateUser(user2);// 未执行

if (affectedCount ==1 && affectedCount2 ==1) {

return1;

}

return0;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,039评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,898评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,314评论 19 139
  • application的配置属性。 这些属性是否生效取决于对应的组件是否声明为Spring应用程序上下文里的Bea...
    新签名阅读 10,760评论 1 27
  • 这些属性是否生效取决于对应的组件是否声明为 Spring 应用程序上下文里的 Bean(基本是自动配置的),为一个...
    发光的鱼阅读 5,257评论 0 14