SSM框架整合-进行注解式和XML配置式事务管理

  • MYSQL 表的类型必须是INNODB才支持事务

    在Mysql中,只有当表的类型是INNODB的时候,才支持事务,所以需要把表的类型设置为INNODB,否则无法观察到事务.
    修改表的类型为INNODB的SQL:
    alter table category_ ENGINE  = innodb;

    查看表的类型的SQL
    show table status from how2java; 

    不过有个前提,就是当前的MYSQL服务器本身要支持INNODB,如果不支持,请看 开启MYSQL INNODB的办法
  • 导入JAR包

    做事务管理需要额外的jar才行,aspectjweaver.jar
    把jar包导入到项目中,导包办法:右键 project->properties->java build path->libaries->add external jars
  • CategoryService

    为接口CategoryService增加addTwo和deleteAll方法
    package com.how2java.service;
     
    import java.util.List;
     
    import com.how2java.pojo.Category;
     
    public interface CategoryService {
     
        List<Category> list();
         
        void addTwo();
     
        void deleteAll();
     
    }
  • CategoryServiceImpl

    在CategoryServiceImpl中实现deleteAll和addTwo方法。
    分别做如下事情:
    1. 删除所有Category
    2. 增加2个Category对象,第一个可以正常增加,第二个因为名字太长,加入会失败。
    package com.how2java.service.impl;
     
    import java.util.List;
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
     
    import com.how2java.mapper.CategoryMapper;
    import com.how2java.pojo.Category;
    import com.how2java.service.CategoryService;
     
    @Service
    public class CategoryServiceImpl  implements CategoryService{
        @Autowired
        CategoryMapper categoryMapper;
         
        public List<Category> list(){
            return categoryMapper.list();
        }
     
        public void deleteAll() {
            List<Category> cs = list();
            for (Category c : cs) {
                 
                categoryMapper.delete(c.getId());
            }
        }
         
        @Override
        public void addTwo() {
             
            Category c1 = new Category();
            c1.setName("短的名字");
            categoryMapper.add(c1);
             
            Category c2 = new Category();
            c2.setName("名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,");
            categoryMapper.add(c2);
        };
     
    }
  • 修改测试类,观察效果

    修改测试类MybatisTest :注入CategoryService 对象,并调用deleteAll和addTwo方法,运行后在数据库中发现只有只有一条数据插入成功了,说明addTwo方法不是事务管理的。 如果是事务管理的,那么就应该都成功,或者都失败。

    package com.how2java.test;
     
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     
    import com.how2java.service.CategoryService;
     
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class MybatisTest {
     
        @Autowired
        private CategoryService categoryService;
     
        @Test
        public void testAddTwo() {
            categoryService.deleteAll();
            categoryService.addTwo();
             
        }
     
    }
  • 进行事务配置

    修改applicationContext.xml,添加事务管理器和事务注解扫描器
    <?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:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
         
       <context:annotation-config />
        <context:component-scan base-package="com.how2java.service" />
     
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
          <property name="driverClassName"> 
              <value>com.mysql.jdbc.Driver</value> 
          </property> 
          <property name="url"> 
              <value>jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8</value> 
         
          </property> 
          <property name="username"> 
              <value>root</value> 
          </property> 
          <property name="password"> 
              <value>admin</value> 
          </property>    
        </bean>
         
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="typeAliasesPackage" value="com.how2java.pojo" />
            <property name="dataSource" ref="dataSource"/>
            <property name="mapperLocations" value="classpath:com/how2java/mapper/*.xml"/>
        </bean>
     
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.how2java.mapper"/>
        </bean>
         
        <tx:annotation-driven transaction-manager="transactionManager"/>
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
         
    </beans>
  • 使用注解方式

    为addTwo方法加上事务注解
    package com.how2java.service.impl;
     
    import java.util.List;
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
     
    import com.how2java.mapper.CategoryMapper;
    import com.how2java.pojo.Category;
    import com.how2java.service.CategoryService;
     
    @Service
    public class CategoryServiceImpl  implements CategoryService{
        @Autowired
        CategoryMapper categoryMapper;
         
        public List<Category> list(){
            return categoryMapper.list();
        }
     
        public void deleteAll() {
            List<Category> cs = list();
            for (Category c : cs) {
                 
                categoryMapper.delete(c.getId());
            }
        }
         
        @Override
        @Transactional(propagation=Propagation.REQUIRED,rollbackForClassName="Exception")
        public void addTwo() {
             
            Category c1 = new Category();
            c1.setName("短的名字");
            categoryMapper.add(c1);
             
            Category c2 = new Category();
            c2.setName("名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,名字长对应字段放不下,");
            categoryMapper.add(c2);
        };
     
    }
  • 运行测试类,观察效果

    运行测试类MybatisTest发现数据库里是空的。因为第二个数据插入不进去,所以第一个数据的插入也回滚了。
  • 使用XML配置方式

    修改applicationContext,以支持AOP方式
    <?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:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
         
       <context:annotation-config />
        <context:component-scan base-package="com.how2java.service" />
     
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
          <property name="driverClassName"> 
              <value>com.mysql.jdbc.Driver</value> 
          </property> 
          <property name="url"> 
              <value>jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8</value> 
         
          </property> 
          <property name="username"> 
              <value>root</value> 
          </property> 
          <property name="password"> 
              <value>admin</value> 
          </property>    
        </bean>
         
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="typeAliasesPackage" value="com.how2java.pojo" />
            <property name="dataSource" ref="dataSource"/>
            <property name="mapperLocations" value="classpath:com/how2java/mapper/*.xml"/>
        </bean>
     
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.how2java.mapper"/>
        </bean>
         
    <!--     <tx:annotation-driven transaction-manager="transactionManager"/> -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
         
        <tx:advice id="txadvice" transaction-manager="transactionManager"> 
            <tx:attributes> 
                <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" /> 
                <tx:method name="del*" propagation="REQUIRED" rollback-for="Exception"/>
                <tx:method name="edit*" propagation="REQUIRED" rollback-for="Exception" />
                <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/> 
                <tx:method name="list*" propagation="REQUIRED" rollback-for="Exception"/> 
            </tx:attributes> 
        </tx:advice> 
            
        <aop:config> 
            <aop:pointcut id="serviceMethod" expression="execution(* com.how2java.service.*.*(..))"/> 
            <aop:advisor pointcut-ref="serviceMethod" advice-ref="txadvice"/> 
        </aop:config>      
     
    </beans>
  • 运行测试类,观察效果

    运行MybatisTest可以看到一样的事务效果,即都没有插入成功
  • 为什么不启动Web应用进行测试?

    为什么不启动Web应用进行测试? 而是要用一个MybatisTest这种方式?
    因为根据前面的教材,都是基于一个实体类做管理的ssm应用,不方便重现事务出问题的现象。
    通过本教材的方式,也是修改Service以提供事务管理的支持,其效果也是能够运用在web应用的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值