Spring MVC 事务配置及使用

来源:互联网 发布:淘宝卖家怎么拉黑买家 编辑:程序博客网 时间:2024/06/06 03:33
如有不同意见请果断指出 !Spring <wbr>MVC <wbr>事务配置及使用
声明:javaweb项目  框架为SpringMVC+MyBatis
因事务配置属于springMVC/Mybatis框架的模块化配置,所以此处也仅先介绍 "事务配置" 这一配置的详解;
首先需要知晓springMVC+Mybatis框架搭建需要的几个xml文件:
spring-servlet.xml,applicationContext.xml等,看项目需要进行选择性添加其他的xml文件。
而我们这里需要讲解的则是applicationContext.xml文件,因为这个文件在项目中是必须要有的。至于文件位置则需要在web.xml中进行指定;

例如 : web.xml代码如下:
 
    contextConfigLocation
   
        /WEB-INF/applicationContext.xml
        /WEB-INF/spring-servlet.xml
       
 

SpringMVC编程式事务管理与SpringMVC声明式事务管理:
编程式事务管理 需要在处理逻辑时加入 begin开始事务,commit提交事务,close关闭事务。
声明式事务管理 需要在配置文件中进行相关配置,书写代码时可减少书写量。
我们这里主要 介绍的就是“声明式事务管理”


 SpringMvc的声明式事务配置:

1.需要创建一个applicationContext.xml文件;(项目中原本就存在的话,不用创建)
首先在文件中添加该文件的声明:
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring- tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

  2.然后在该文件内添加bean标签进行数据库访问配置:

classpath:resouces.properties
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
//获取且使用resource.properties中保存的数据库信息。
jdbc.minPoolSize}"/>
 
jdbc.maxIdleTime}"/>


  3.引用配置的数据库访问设置进行事务配置(声明式事务管理):
 "org.springframework.jdbc.datasource.DataSourceTransactionManager" scope="">
//引用上面代码的dataSource
dataSource">

 至此,applicationContext.xml文件中的事务配置结束 。

  配置好了,如何使用事务呢?

好,在一个模拟的Controller里面举一个例子:
首先需要注入一个对象:
@Autowired
//Spring声明式事务管理提供的一个接口,供多个平台使用。
       private PlatformTransactionManager platformTransactionManager; 

public void  testTransactionManager(User u){
DefaultTransactionDefinition def = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);

TransactionStatus status = platformTransactionManager.gerTransaction(def);
boolean b = userService.insert(user);
//如果插入成功则提交事务,若未提交成功则回滚事务。
if(b==true){
platformTransactionManager.commit(status);
}else{
platformTransactionManager.rollback(status);
}
}

bingo..OK。
0 0
原创粉丝点击