spring配置里面的事物管理

在前面我们介绍的都是基于注解的方式来使用事务,现在来学习下基于XML的方式怎样来配置事务,先把PersonServiceBean.java里的注解去掉,
PersonServiceBean.java
Java代码
  1. package cn.itcast.service.impl;
  2. import java.util.List;
  3. import javax.sql.DataSource;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import cn.itcast.bean.Person;
  6. import cn.itcast.service.PersonService;
  7. public class PersonServiceBean implements PersonService {
  8. private JdbcTemplate jdbcTemplate;
  9. public void setDataSource(DataSource dataSource) {
  10. this.jdbcTemplate = new JdbcTemplate(dataSource);
  11. }
  12. public void delete(Integer personid) throws Exception{
  13. jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
  14. new int[]{java.sql.Types.INTEGER});
  15. }
  16. public Person getPerson(Integer personid) {
  17. return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid},
  18. new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());
  19. }
  20. @SuppressWarnings("unchecked")
  21. public List<Person> getPersons() {
  22. return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());
  23. }
  24. public void save(Person person) {
  25. jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},
  26. new int[]{java.sql.Types.VARCHAR});
  27. }
  28. public void update(Person person) {
  29. jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},
  30. new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
  31. }
  32. }
  1. package cn.itcast.service.impl;
  2. import java.util.List;
  3. import javax.sql.DataSource;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import cn.itcast.bean.Person;
  6. import cn.itcast.service.PersonService;
  7. public class PersonServiceBean implements PersonService {
  8. private JdbcTemplate jdbcTemplate;
  9. public void setDataSource(DataSource dataSource) {
  10. this.jdbcTemplate = new JdbcTemplate(dataSource);
  11. }
  12. public void delete(Integer personid) throws Exception{
  13. jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
  14. new int[]{java.sql.Types.INTEGER});
  15. }
  16. public Person getPerson(Integer personid) {
  17. return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid},
  18. new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());
  19. }
  20. @SuppressWarnings("unchecked")
  21. public List<Person> getPersons() {
  22. return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());
  23. }
  24. public void save(Person person) {
  25. jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},
  26. new int[]{java.sql.Types.VARCHAR});
  27. }
  28. public void update(Person person) {
  29. jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},
  30. new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
  31. }
  32. }
package cn.itcast.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public void delete(Integer personid) throws Exception{
		jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
				new int[]{java.sql.Types.INTEGER});
	}
	
	public Person getPerson(Integer personid) {		
		return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid}, 
				new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());
	}

	@SuppressWarnings("unchecked")
	public List<Person> getPersons() {
		return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());
	}

	public void save(Person person) {
		jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},
				new int[]{java.sql.Types.VARCHAR});
	}

	public void update(Person person) {
		jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},
				new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
	}
}


目前这个bean是不受Spring管理的,我们通过配置文件的方式,在XML文件中对这个bean进行事务配置。
如果我们采用基于XML方式来配置事务的话,beans.xml里的<tx:annotation-driven transaction-manager="txManager"/>
这个就不再需要使用,删掉。
我们介绍下,如何使用基于XML方式配置事务,


采用基于XML方式配置事务
--------------------------------------------------------------------

Xml代码 复制代码
  1. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  2. <property name="dataSource" ref="dataSource"/>
  3. </bean>
  4. <aop:config>
  5. <aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
  6. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
  7. </aop:config>
  8. <tx:advice id="txAdvice" transaction-manager="txManager">
  9. <tx:attributes>
  10. <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
  11. <tx:method name="*"/>
  12. <!--其它方法使用默认的事务行为-->
  13. </tx:attributes>
  14. </tx:advice>
  1. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  2. <property name="dataSource" ref="dataSource"/>
  3. </bean>
  4. <aop:config>
  5. <aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
  6. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
  7. </aop:config>
  8. <tx:advice id="txAdvice" transaction-manager="txManager">
  9. <tx:attributes>
  10. <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
  11. <tx:method name="*"/>
  12. <!--其它方法使用默认的事务行为-->
  13. </tx:attributes>
  14. </tx:advice>



我们配置了一个<aop:config>,里面的切入点pointcut,它对哪些方法进行拦截呢?对cn.itcast.service这个包,及其子包底下的所有类的所有方法,实现拦截。 拦截到方法后,运用一个advisor(通知),这个通知大家要注意,Spring里面已经给我们提供了一个事务通知了,通过<aop:advisor advice-ref...这个配置把它引入进来,这个通知,使用了上面的切入点,也就是说当拦截到这些业务方法的执行的时候呢,它会交给txAdvice这个事务通知进行处理.
txAdvice这个bean的定义,实际上在Spring容器里它也会注册一个事务管理器,应该说是注册一个通知管理器,专门用来做事务处理的这么一个bean。

接下来配置beans.xml

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  11. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  12. <context:property-placeholder location="classpath:jdbc.properties"/>
  13. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  14. <property name="driverClassName" value="${driverClassName}"/>
  15. <property name="url" value="${url}"/>
  16. <property name="username" value="${username}"/>
  17. <property name="password" value="${password}"/>
  18. <!-- 连接池启动时的初始值 -->
  19. <property name="initialSize" value="${initialSize}"/>
  20. <!-- 连接池的最大值 -->
  21. <property name="maxActive" value="${maxActive}"/>
  22. <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
  23. <property name="maxIdle" value="${maxIdle}"/>
  24. <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
  25. <property name="minIdle" value="${minIdle}"/>
  26. </bean>
  27. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  28. <property name="dataSource" ref="dataSource"/>
  29. </bean>
  30. <aop:config>
  31. <aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
  32. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
  33. </aop:config>
  34. <tx:advice id="txAdvice" transaction-manager="txManager">
  35. <tx:attributes>
  36. <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
  37. <tx:method name="*"/>
  38. </tx:attributes>
  39. </tx:advice>
  40. <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
  41. <property name="dataSource" ref="dataSource"/>
  42. </bean>
  43. </beans>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  11. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  12. <context:property-placeholder location="classpath:jdbc.properties"/>
  13. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  14. <property name="driverClassName" value="${driverClassName}"/>
  15. <property name="url" value="${url}"/>
  16. <property name="username" value="${username}"/>
  17. <property name="password" value="${password}"/>
  18. <!-- 连接池启动时的初始值 -->
  19. <property name="initialSize" value="${initialSize}"/>
  20. <!-- 连接池的最大值 -->
  21. <property name="maxActive" value="${maxActive}"/>
  22. <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
  23. <property name="maxIdle" value="${maxIdle}"/>
  24. <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
  25. <property name="minIdle" value="${minIdle}"/>
  26. </bean>
  27. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  28. <property name="dataSource" ref="dataSource"/>
  29. </bean>
  30. <aop:config>
  31. <aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
  32. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
  33. </aop:config>
  34. <tx:advice id="txAdvice" transaction-manager="txManager">
  35. <tx:attributes>
  36. <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
  37. <tx:method name="*"/>
  38. </tx:attributes>
  39. </tx:advice>
  40. <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
  41. <property name="dataSource" ref="dataSource"/>
  42. </bean>
  43. </beans>


配置好事务了,PersonServiceBean这业务bean就可以受事务管理了。现在就可以使用Spring里面的声明式事务对它进行管理了,现在做一下测试,看事务是否应用起来了。
打开单元测试,执行save方法,保存一些数据进去。。
PersonServiceTest.java

Java代码 复制代码
  1. package junit.test;
  2. import org.junit.BeforeClass;
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. import cn.itcast.bean.Person;
  7. import cn.itcast.service.PersonService;
  8. public class PersonServiceTest {
  9. private static PersonService personService;
  10. @BeforeClass
  11. public static void setUpBeforeClass() throws Exception {
  12. try {
  13. ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
  14. personService = (PersonService) cxt.getBean("personService");
  15. } catch (RuntimeException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. @Test public void save(){
  20. for(int i=10; i<15; i++)
  21. personService.save(new Person("传智播客"+ i));
  22. }
  23. ..................................
  24. @Test public void delete(){
  25. try {
  26. personService.delete(3);
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. ..................................
  32. }
  1. package junit.test;
  2. import org.junit.BeforeClass;
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. import cn.itcast.bean.Person;
  7. import cn.itcast.service.PersonService;
  8. public class PersonServiceTest {
  9. private static PersonService personService;
  10. @BeforeClass
  11. public static void setUpBeforeClass() throws Exception {
  12. try {
  13. ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
  14. personService = (PersonService) cxt.getBean("personService");
  15. } catch (RuntimeException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. @Test public void save(){
  20. for(int i=10; i<15; i++)
  21. personService.save(new Person("传智播客"+ i));
  22. }
  23. ..................................
  24. @Test public void delete(){
  25. try {
  26. personService.delete(3);
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. ..................................
  32. }
package junit.test; 
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;

public class PersonServiceTest {
	private static PersonService personService;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
			personService = (PersonService) cxt.getBean("personService");
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}

	@Test public void save(){
		for(int i=10; i<15; i++)
			personService.save(new Person("传智播客"+ i));
	}

	..................................

	@Test public void delete(){
		try {
			personService.delete(3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	..................................
}


现在数据库person表的记录如下:看图


为了进一步验证事务配置起作用了,我们可以这样做

Java代码 复制代码
  1. public void delete(Integer personid) throws Exception{
  2. jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
  3. new int[]{java.sql.Types.INTEGER});
  4. jdbcTemplate.update("delete from person_wrong_name where id=7");
  5. }
  1. public void delete(Integer personid) throws Exception{
  2. jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
  3. new int[]{java.sql.Types.INTEGER});
  4. jdbcTemplate.update("delete from person_wrong_name where id=7");
  5. }
public void delete(Integer personid) throws Exception{
		jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
				new int[]{java.sql.Types.INTEGER});
		jdbcTemplate.update("delete from person_wrong_name where id=7");
	}


在PersonServiceBean.java的delete方法里面,执行两条update语句,默认情况下这两条语句都会在同一个事务里执行,如果说这个方法没有开启事务的话,这两条update语句会在各自的事务里执行(也就是说他们不能在同一事务里执行),我们通过这样来判断delete方法是否开了事务,如果开了事务,两条update语句就在同一事务里执行,如果没开事务,就会在各自的事务里执行,也就是说第二个update语句故意写错了,第二条语句会出错,它是否会引起第一条update语句的回滚呢?如果我们应用上了Spring的事务管理,他必然会一起回滚,如果没应用上的话,第一条update语句是会运行成功的。
运行单元测试的delete方法,

Java代码 复制代码
  1. @Test public void delete(){
  2. try {
  3. personService.delete(3);
  4. } catch (Exception e) {
  5. e.printStackTrace();
  6. }
  7. }
  1. @Test public void delete(){
  2. try {
  3. personService.delete(3);
  4. } catch (Exception e) {
  5. e.printStackTrace();
  6. }
  7. }
@Test public void delete(){
    try {
        personService.delete(3);
    } catch (Exception e) {
        e.printStackTrace();
    }
}



JUnit显示出错,查看数据库person表记录,发现id为3和7的记录还在,如图:



说明开了事务,两条都不被删。
假如我们没有应用事务管理的话,在beans.xml里,把下面的语句注释掉

Xml代码 复制代码
  1. <!--
  2. <aop:config>
  3. <aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
  4. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
  5. </aop:config>
  6. <tx:advice id="txAdvice" transaction-manager="txManager">
  7. <tx:attributes>
  8. <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
  9. <tx:method name="*"/>
  10. </tx:attributes>
  11. </tx:advice>
  12. -->
  1. <!--
  2. <aop:config>
  3. <aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
  4. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
  5. </aop:config>
  6. <tx:advice id="txAdvice" transaction-manager="txManager">
  7. <tx:attributes>
  8. <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
  9. <tx:method name="*"/>
  10. </tx:attributes>
  11. </tx:advice>
  12. -->


看下当我们没有应用Spring的事务管理器的时候,它是否能删除id=3这条记录(既是第一个update语句顺利提交不回滚)呢?
现在数据库person表的记录如下,看图:


运行单元测试的delete方法,JUnit说运行时出错,看数据库,如图:


id=3的记录不见了,id=7的记录还存在,这代表,事务管理器没有应用上,因为第一条update语句是在一个事务里执行,第二条update语句是在另一个事务里执行,因为它没有应用上Spring提供的事务管理,所以说他们两个update语句会在单独的事务中执行。 第一条是执行成功的,第二条是执行失败的。我们通过观察结果就可以看到它目前并没有应用上事务管理,所以一定要注意:以后在开发的时候,一定要确保你们的bean是受Spring的事务管理的。如果不受管理的话,你们就无法应用Spring给我们提供的这些功能,也就是说业务方法开启的时候给我们打开事务,在业务方法结束的时候根据运行情况如果没有抛出运行期例外的话,那么它就给我们提交事务,否则它就给我们回滚事务,这点大家是要注意的。

基于XML方式使用事务就给大家介绍完了,具体使用XML方式配置事务,还是使用注解方式配置事务,Spring开发团队就建议我们采用注解方式来配置事务,因为采用注解方式来使用事务的话,我们的配置可以做到精确控制,可以针对某一个方法,使用起来比较灵活。如果采用配置方式为某个业务方法定义某些事务行为的话,那么这个配置文件配置内容会很臃肿,所以Spring的开发团队建议我们采用注解方式来配置事务。
但是目前在企业开发中,目前大部分项目使用的还是基于XML配置方式来使用事务,但是以后很多新项目也慢慢开始转向到了注解方式,这两种方式大家都需要去熟悉。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值