Spring + Mybatis+事务

SM

配置
在这里插入图片描述

SqlMapConfig.xml

<configuration>
    <!--设置日志输出语句,显示相应操作的sql语名-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>

mapper.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--读取属性文件jdbc.properties-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>
    <!--创建数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置SqlSessionFactoryBean类-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--配置MyBatis的核心配置文件-->
        <property name="configLocation" value="SqlMapConfig.xml"></property>
        <!--注册实体类的别名-->
        <property name="typeAliasesPackage" value="com.bjpowernode.pojo"></property>
    </bean>
    <!--注册mapper.xml文件-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjpowernode.mapper"></property>
    </bean>
</beans>

service

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--导入applicationContext_mapper.xml文件-->
    <import resource="applicationContext_mapper.xml"></import>
    <!--SM是基于注解的开发,所以添加包扫描-->
    <context:component-scan base-package="com.bjpowernode.service.impl"></context:component-scan>
    <!--事务处理-->

    <!--1.添加事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--因为事务必须关联数据库处理,所以要配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
     </bean>

    <!--2.添加事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

trans,事务配置

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--导入applicationContext_mapper.xml文件-->
    <import resource="applicationContext_mapper.xml"></import>
    <!--SM是基于注解的开发,所以添加包扫描-->
    <context:component-scan base-package="com.bjpowernode.service.impl"></context:component-scan>
    <!--事务处理-->

    <!--1.添加事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--因为事务必须关联数据库处理,所以要配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
     </bean>

    <!--2.添加事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123

在这里插入图片描述
Mapper
AccountsMapper

public interface AccountsMapper {

    //增加帐户
    int save(Accounts accounts);
}

AccountsMapper.xml

<mapper namespace="com.mapper.AccountsMapper">

    <!--
      //增加帐户
    int save(Accounts accounts);
    private Integer aid;
    private String aname;
    private String acontent;
    -->
    <insert id="save" parameterType="accounts">
        insert into accounts values(#{aid},#{aname},#{acontent})
    </insert>
</mapper>

UserMapper

public interface UsersMapper {
    int insert(Users users);
}

UserMapper.xml

<mapper namespace="com.mapper.UsersMapper">

    <!--
       int insert(Users users);
       实体类
        private Integer userid;
        private String username;
        private String upass;
    -->
    <insert id="insert" parameterType="users">
        insert into users values(#{userid},#{username},#{upass})
    </insert>
</mapper>

pojo
Accounts

public class Accounts {
    private Integer aid;
    private String aname;
    private String acontent;
}

Users

public class Users {
    private Integer userid;
    private String username;
    private String upass;
}

service
AccountsService

public interface AccountsService {
    int save(Accounts accounts);
}

UserService

public interface UsersService {
    //增加用户
    int insert(Users users);
}

service.Impl
AccountsServiceImpl

@Service
public class AccountsServiceImpl implements AccountsService {
    //一定会有数据访问层的对象
    @Autowired
    AccountsMapper accountsMapper;
    @Override
    public int save(Accounts accounts) {
        int num = 0;
        num = accountsMapper.save(accounts);
        System.out.println("增加帐户成功!num="+num);
        //手工抛出异常
        System.out.println(1/0);
        return num;
    }
}

UserServiceImpl

@Service  //交给Spring去创建对象
public class UsersServiceImpl implements UsersService {
    //切记切记:在所有的业务逻辑层中一定会有数据访问层的对象
    /**
     *         @Autowired相当于做了以下事情 创建SqlSession,然后提交或回滚
     *         //1.读取核心配置文件
     *         InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
     *         //2.创建工厂对象
     *         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
     *         //3.取出sqlSession
     *         sqlSession = factory.openSession(true);//自动提交事务
     *         //4.取出动态代理的对象,完成接口中方法的调用,实则是调用xml文件中相的标签的功能
     *         uMapper = sqlSession.getMapper(UsersMapper.class);
     */
    @Autowired
    UsersMapper usersMapper;

    @Autowired
    AccountsService accountsService;

    @Override
    public int insert(Users users) {
        int num = usersMapper.insert(users);
        System.out.println("用户增加成功!num="+num);

        //调用帐户的增加操作,调用的帐户的业务逻辑层的功能
        num = accountsService.save(new Accounts(300,"王五","帐户好的呢!"));
        return num;
    }
}

测试

    @Test
    public void testTrans(){
        //创建容器并启动
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_trans.xml");
        //取出UsersServiceImpl
        UsersService uService = (UsersService) ac.getBean("usersServiceImpl");
        int num = uService.insert(new Users(100,"张三","123"));
        System.out.println(num);
    }

添加事务

基于注解的事务添加步骤

1)在applicationContext_service.xml文件中添加事务管理器

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--因为事务必须关联数据库处理,所以要配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
     </bean>

2)在applicationContext_service.xml文件中添加事务的注解驱动

<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

3)在业务逻辑的实现类上添加注解@Transactional(propagation = Propagation.REQUIRED)
REQUIRED表示增删改操作时必须添加的事务传播特性

@Transactional注解参数详解
	@Transactional(propagation = Propagation.REQUIRED,//事务的传播特性
	        noRollbackForClassName = "ArithmeticException", //指定发生什么异常不回滚,使用的是异常的名称
	        noRollbackFor = ArithmeticException.class,//指定发生什么异常不回滚,使用的是异常的类型
	        rollbackForClassName = "",//指定发生什么异常必须回滚
	        rollbackFor = ArithmeticException.class,//指定发生什么异常必须回滚
	        timeout = -1, //连接超时设置,默认值是-1,表示永不超时
	        readOnly = false, //默认是false,如果是查询操作,必须设置为true.
	        isolation = Isolation.DEFAULT//使用数据库自已的隔离级别        
	)

Spring的两种事务处理方式
1)注解式的事务
使用@Transactional注解完成事务控制,此注解可添加到类上,则对类中所有方法执行事务的设定.此注解可添加到方法上,只是对此方法执行事务的处理.

2)声明式事务(必须掌握),在配置文件中添加一次,整个项目遵循事务的设定.

Spring中事务的五大隔离级别

1).未提交读(Read Uncommitted):允许脏读,也就是可能读取到其他会话中未提交事务修改的数据
2).提交读(Read Committed):只能读取到已经提交的数据。Oracle等多数数据库默认都是该级别 (不重复读)
3).可重复读(Repeated Read):可重复读。在同一个事务内的查询都是事务开始时刻一致的,InnoDB默认级别。在SQL标准中,该隔离级别消除了不可重复读,但是还存在幻象读,但是innoDB解决了幻读
4).串行读(Serializable):完全串行化的读,每次读都需要获得表级共享锁,读写相互都会阻塞
5).使用数据库默认的隔离级别isolation = Isolation.DEFAULT
MySQL:mysql默认的事务处理级别是’REPEATABLE-READ’,也就是可重复读
Oracle:oracle数据库支持READ COMMITTED 和 SERIALIZABLE这两种事务隔离级别。默认系统事务隔离级别是READ COMMITTED,也就是读已提交

为什么添加事务管理器

JDBC: Connection con.commit(); con.rollback();
MyBatis: SqlSession sqlSession.commit(); sqlSession.rollback();
Hibernate: Session session.commit(); session.rollback();
不同技术的操作是不一样的
事务管理器用来生成相应技术的连接+执行语句的对象.
如果使用MyBatis框架,必须使用DataSourceTransactionManager类完成处理
加了之后就可以去生成SqlSession 然后去完成提交或回滚

     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--因为事务必须关联数据库处理,所以要配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
     </bean>

项目中的所有事务,必须添加到业务逻辑层上.

Spring事务的传播特性

@Transactional(propagation = Propagation.REQUIRED,//事务的传播特性
多个事务之间的合并,互斥等都可以通过设置事务的传播特性来解决.
常用
PROPAGATION_REQUIRED:必被包含事务(增删改就用这个)
PROPAGATION_REQUIRES_NEW:自己新开事务,不管之前是否有事务
PROPAGATION_SUPPORTS:支持事务,如果加入的方法有事务,则支持事务,如果没有,不单开事务
PROPAGATION_NEVER:不能运行中事务中,如果包在事务中,抛异常
PROPAGATION_NOT_SUPPORTED:不支持事务,运行在非事务的环境
不常用
PROPAGATION_MANDATORY:必须包在事务中,没有事务则抛异常
PROPAGATION_NESTED:嵌套事务

声明式事务

Spring非常有名的事务处理方式.声明式事务.
要求项目中的方法命名有规范
1)完成增加操作包含 add save insert set
2)更新操作包含 update change modify
3)删除操作包含 delete drop remove clear
4)查询操作包含 select find search get
也就是说,如果你的方法名带有这些名称,就会调用对应的事务配置

配置事务切面时可以使用通配符*来匹配所有方法

<!--添加事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事务切面-->
    <tx:advice id="myadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*select*" read-only="true"/>
            <tx:method name="*find*" read-only="true"/>
            <tx:method name="*search*" read-only="true"/>
            <tx:method name="*get*" read-only="true"/>
            <tx:method name="*insert*" propagation="REQUIRED" no-rollback-for="ArithmeticException"/>
            <tx:method name="*add*" propagation="REQUIRED"/>
            <tx:method name="*save*" propagation="REQUIRED" no-rollback-for="ArithmeticException"/>
            <tx:method name="*set*" propagation="REQUIRED"/>
            <tx:method name="*update*" propagation="REQUIRED"/>
            <tx:method name="*change*" propagation="REQUIRED"/>
            <tx:method name="*modify*" propagation="REQUIRED"/>
            <tx:method name="*delete*" propagation="REQUIRED"/>
            <tx:method name="*remove*" propagation="REQUIRED"/>
            <tx:method name="*drop*" propagation="REQUIRED"/>
            <tx:method name="*clear*" propagation="REQUIRED"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    <!--绑定切面和切入点-->
    <aop:config>
        <aop:pointcut id="mycut" expression="execution(* com.bjpowernode.service.impl.*.*(..))"></aop:pointcut>
        <aop:advisor  advice-ref="myadvice" pointcut-ref="mycut"></aop:advisor>
    </aop:config>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值