转自http://blog.csdn.net/yeson6/article/details/4954330
学了springmvc后最大的困扰就是事务管理问题了,感觉最大的困扰就是事务管理了,网上的方法太多太乱了,大多数还是用hibernate的,今天看了上面大侠的文章后终于搞通了,而且配置起来就简单快捷。
首先applicationContext.xml下:
表头:
<!-- 声明式事务控制 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 用注解来实现事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
接着加入:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName">
最后在service层或者serviceimpl层配置好@Transactional:
package com.wy.service;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.wy.dao.Mydao;
import com.wy.dao.Testdao;
import com.wy.model.Disease;
/**
* Service业务逻辑层
* @author Maxldwy
*
*/
@Transactional
@Service("testservice")
public class Testservice {
@Autowired
private Testdao testdao;//测试多个dao和对应的mapper xml文件 可行
@Transactional(isolation = Isolation.READ_COMMITTED)
public void test() throws Exception{
testdao.insert1("accasd等撒旦撒");
System.out.println("insert");
testdao.update1("b啊实打实大");
System.out.println("update");
}
}
好了。通了。出现错误后会发生事务回滚~
我用的是mybatis+springmvc框架,所以这里直接连dao层去操作数据库了,这样写最简单方便哈~