其他分享
首页 > 其他分享> > Spring 整合 Mybatis 并开启事务

Spring 整合 Mybatis 并开启事务

作者:互联网

基于XML

项目结构图

pom.xml


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.16</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.16</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>

       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.8</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory><!--所在的目录-->
                <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

配置Spring applicationContext.xml

  1. 在jdbc.properties文件内配置数据库、username等相关信息
jdbc.url = jdbc:mysql://127.0.0.1:3306/test
jdbc.username = root
jdbc.password = root
jdbc.maxActive = 20
  1. 配置数据源
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean>
  1. 配置SessionFactory
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="mapperLocations" value="classpath:com/taiji/dao/impl/*.xml"/>
       <property name="typeAliasesPackage" value="com.taiji.pojo"/>
   </bean>

  1. 配置mapper接口扫描
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.taiji.dao"/>
    </bean>
  1. 配置service层内的类
    <bean id="accountService" class="com.taiji.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

Java代码

  1. 写 dao (或mapper)层
package com.taiji.dao;

import org.apache.ibatis.annotations.Param;

public interface AccountDao {
    void inMoney(@Param("name") String name, @Param("money") double money);
    void outMoney(@Param("name") String name,@Param("money") double money);
}

  1. 写 mapper.xml
<?xml version="1.0" encoding="UTF8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taiji.dao.AccountDao">
    <!--void inMoney(String outName,double money);-->
    <update id="inMoney">
        update bank
        set money = money + #{money}
        where name = #{name}
    </update>

    <!--void outMoney(String outName,double money);-->
    <update id="outMoney">
        update bank
        set money = money - #{money}
        where name = #{name}
    </update>

</mapper>
  1. service
package com.taiji.service;

public interface AccountService {
    /**
     * 转账操作
     *
     * @param outName 出账用户名
     * @param inName  入账用户名
     * @param money   转账金额
     */
    void transfer(String outName, String inName, Double money);
}

  1. service实现
package com.taiji.service.impl;

import com.taiji.dao.AccountDao;
import com.taiji.service.AccountService;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public AccountServiceImpl(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public void transfer(String outName, String inName, Double money) {

        accountDao.inMoney(outName, money);
        int i = 1 / 0;
        accountDao.outMoney(inName, money);

    }
}

测试类(未使用Spring-Test)

package com.taiji.serviceTest;

import com.taiji.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AccountTest {
    @Test
    public void test01() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = context.getBean(AccountService.class);
        accountService.transfer("tom", "jack", 500.0);
    }
}

未开始事务总结

扣钱后因为异常导致转账后未收到帐
开启事务,出现异常则回滚

事务配置

  1. 配置平台事务管理器
    <!-- 配置平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
  1. 通知 事务的增强
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" read-only="false"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="a" read-only="false" propagation="REQUIRED"/>
            <tx:method name="b" read-only="false" propagation="NEVER"/>
            <tx:method name="transfer"
                       read-only="false"
                       timeout="-1"
                       isolation="DEFAULT"
                       no-rollback-for=""
                       rollback-for=""
                       propagation="REQUIRED"
            />
        </tx:attributes>
    </tx:advice>
  1. 配置事务的AOP织入
  <aop:config>
       <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.taiji.service.impl.*.*(..))"/>
   </aop:config>

开启事务后的总结

此时service内部方法导致异常不会导致数据库内容修改到一半

标签:accountDao,Spring,开启,money,Mybatis,org,com,public,name
来源: https://www.cnblogs.com/yucoolcoolhan/p/15956778.html