Spring整合MyBatis

通过模拟银行转账的方式来实现Spring整合MyBatis。

一.准备工作

通过navicat创建一个数据库,起名叫my_database。

1.数据库的准备

 (1)建立数据库

(2)数据库表的准备(表名为my_account),建好表后在数据库中加入转账金额

数据库表的内容如下:

 

2.创建Maven项目并添加pom依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>ind.wqy</groupId>
  <artifactId>spring6-011-spring-and-mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <repositories>
    <repository>
      <id>repository.spring.milestone</id>
      <name>Spring Milestone Repository</name>
      <url>https://repo.spring.io/milestone</url>
    </repository>
  </repositories>

  <dependencies>
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>6.0.0-M2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.30</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.11</version>
    </dependency>
    <!--mybatis-spring:mybatis提供的与spring框架集成的依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.7</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>6.0.0-M2</version>
    </dependency>
  </dependencies>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>
</project>

3.创建包并实现pojo类

 (1)在src/main/java下创建包,包名分别为:

        pers.wqy.mapper
        pers.wqy.pojo
        pers.wqy.service
        pers.wqy.service.impl

 (2)在src/test/java下创建包,包名为: pers.wqy.test

 (3)在pers.wqy.pojo下新建Account类,用于封装数据库中传来的用户信息

package pers.wqy.pojo;

/**
 * @author wqy
 * @version 1.0
 * @date 2022/11/12 11:29
 */
public class Account {
    private Long id;
    private String actno;
    private Double balance;

    public Account() {
    }

    public Account(Long id, String actno, Double balance) {
        this.id = id;
        this.actno = actno;
        this.balance = balance;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", actno='" + actno + '\'' +
                ", balance=" + balance +
                '}';
    }
}

二.Spring与MyBatis整合

 1.编写mapper接口(用于mybatis动态代理生成DAO类)

package pers.wqy.mapper;

import pers.wqy.pojo.Account;

/**
 * @author wqy
 * @version 1.0
 * @date 2022/11/12 11:29
 */
public interface AccountMapper {

    /**
     * 通过actno查询账户信息
     * @param actno
     * @return
     */
    Account selectByActno(String actno);

    /**
     * 通过actno更新账户余额
     * @param account
     * @return
     */
    int updateByActno(Account account);
}

2.编写mapper配置文件

        src/main/resource下新建目录pers/wqy/mapper,并创建AccountMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="pers.wqy.mapper.AccountMapper">
    <!--根据用户的actno查出该用户的所有信息-->
    <select id="selectByActno" resultType="pers.wqy.pojo.Account">
        select id, actno, balance
        from my_account
        where actno = #{actno};
    </select>

    <!--根据用户的actno修改该用户的余额-->
    <update id="updateByActno">
        update my_account
        set balance = #{balance}
        where actno = #{actno};
    </update>
</mapper>

3.编写service接口和service接口实现类

 (1)service接口

package pers.wqy.service;

/**
 * 业务编写
 *
 * @author wqy
 * @version 1.0
 * @date 2022/11/12 11:38
 */
public interface AccountService {

    /**
     * 转账
     * @param from  转出账户的actno
     * @param to    转入账户的actno
     * @param money 转账金额
     */
    void transfer(String from, String to, Double money);
}

(2)service接口的实现类

package pers.wqy.service.impl;

import pers.wqy.mapper.AccountMapper;
import pers.wqy.pojo.Account;
import pers.wqy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wqy
 * @version 1.0
 * @date 2022/11/12 11:39
 */
@Transactional
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper mapper;

    @Override
    public void transfer(String from, String to, Double money) {
        Account fromAct = mapper.selectByActno(from);
        Account toAct = mapper.selectByActno(to);
        //转账金额不足
        if (fromAct.getBalance() < money) {
            throw new RuntimeException("转账金额不足异常");
        }
        //转账金额充足即转账
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);
        //更新数据库
        int i = mapper.updateByActno(fromAct);

        /*//模拟网络异常
        System.out.println(10 / 0);*/

        i += mapper.updateByActno(toAct);
        //判断转账是否成功
        if (i != 2) {
            throw new RuntimeException("转账失败异常");
        }
        System.out.println("转账成功!");
    }

    public AccountMapper getMapper() {
        return mapper;
    }
}

4.在resource目录下编写jdbc.properties配置文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/my_database
jdbc.username=xxx
jdbc.password=xxx

5.在resource目录下编写mybatis-config.xml配置文件

        mybatis-config.xml中大部分的配置可以转移到spring配置文件中,如果遇到mybatis的系统级配置,那就必须需要mybatis-config.xml文件。由于我这里没有,就不需要mybatis-config.xml配置文件了。

6.在resource目录下编写spring.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"
       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 http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

   <!--
       (spring集成mybatis)spring.xml配置文件的编写步骤
        ○ 组件扫描
        ○ 引入外部的属性文件
        ○ 数据源
        ○ SqlSessionFactoryBean配置
            ■ 注入mybatis核心配置文件路径
            ■ 指定别名包
            ■ 注入数据源
        ○ Mapper扫描配置器
            ■ 指定扫描的包
        ○ 事务管理器DataSourceTransactionManager
            ■ 注入数据源
        ○ 启用事务注解
            ■ 注入事务管理器
    -->

    <!--组件扫描-->
    <context:component-scan base-package="pers.wqy"/>
    <!--引入外部的属性文件-->
    <context:property-placeholder location="jdbc.properties"/>
    <!--数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--SqlSessionFactoryBean配置-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="pers.wqy.pojo"/>
    </bean>

    <!--Mapper扫描配置器,生成代理类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="pers.wqy.mapper"/>
    </bean>
    <!--事务管理器DataSourceTransactionManager-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--启用事务注解-->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>

项目目录结构如下:


 

到此为止,spring集成mybatis的步骤全部结束,我们可以写一个测试类测试一下

package pers.wqy.test;

import pers.wqy.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author wqy
 * @version 1.0
 * @date 2022/11/12 11:46
 */
public class TestSpringCombinedMyBatis {

    @Test
    public void test() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccountService service = applicationContext.getBean("accountService", AccountService.class);
        service.transfer("act001", "act002", 10000.00);
    }
}

结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WqyEnergetic

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值