Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

1. Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

@


每博一文案

理想主义的花 终将盛开在浪漫主义的土壤里 我的热情 永远不会熄灭在现实主义的平凡里 我们终将上岸,阳光万里 

2. 大概的实现步骤概述

  1. 第一步:准备数据库表
  • 使用t_act表(账户表)

  1. 第二步:IDEA中创建一个模块,并引入依赖
      • spring-context
      • spring-jdbc
      • mysql驱动
      • mybatis
      • mybatis-spring:mybatis提供的与spring框架集成的依赖
      • 德鲁伊连接池
      • junit
  1. 第三步:基于三层架构实现,所以提前创建好所有的包
      • com.powernode.bank.mapper
      • com.powernode.bank.service
      • com.powernode.bank.service.impl
      • com.powernode.bank.pojo
  1. 第四步:编写pojo
  • Account,属性私有化,提供公开的setter getter和toString。

  1. 第五步:编写mapper接口
  • AccountMapper接口,定义方法

  1. 第六步:编写mapper配置文件
  • 在配置文件中配置命名空间,以及每一个方法对应的sql。

  1. 第七步:编写service接口和service接口实现类
      • AccountService
      • AccountServiceImpl
  1. 第八步:编写jdbc.properties配置文件
  • 数据库连接池相关信息

  1. 第九步:编写mybatis-config.xml配置文件
      • 该文件可以没有,大部分的配置可以转移到spring配置文件中。
      • 如果遇到mybatis相关的系统级配置,还是需要这个文件。
  1. 第十步:编写spring.xml配置文件
      • 组件扫描
      • 引入外部的属性文件
      • 数据源
      • SqlSessionFactoryBean配置
        • 注入mybatis核心配置文件路径
        • 指定别名包
        • 注入数据源
      • Mapper扫描配置器
        • 指定扫描的包
      • 事务管理器DataSourceTransactionManager
        • 注入数据源
      • 启用事务注解
        • 注入事务管理器
  1. 第十一步:编写测试程序,并添加事务,进行测试

3. 详细实现操作步骤

具体实现内容:我们运用 Spring6 和 MyBatis 实现一个转账操作(该转账操作,进行一个事务上的控制,运用 MyBatis 执行 SQL 语句)。

  1. 第一步:准备数据库表
  • 使用t_act表(账户表)

连接数据库的工具有很多,这里我们可以使用IDEA工具自带的 DataBase 插件。可以根据下图提示自行配置:

一般是在 IDEA 的左边,DataBase

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

如下是 t_act 的表结构

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

如下是 t_act 的表数据内容:

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

  1. 第二步:IDEA中创建一个模块,并引入依赖
      • spring-context
      • spring-jdbc
      • mysql驱动
      • mybatis
      • mybatis-spring:mybatis提供的与spring框架集成的依赖
      • 德鲁伊连接池
      • junit

我们先在pom.xml 配置文件当中导入相关的 jar 包信息:

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

<?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>com.rainbowsea</groupId>     <artifactId>spring6-016-mybaits</artifactId>     <version>1.0-SNAPSHOT</version>     <packaging>jar</packaging>      <properties>         <maven.compiler.source>17</maven.compiler.source>         <maven.compiler.target>17</maven.compiler.target>     </properties>     <!--仓库-->     <repositories>         <!--spring里程碑版本的仓库-->         <repository>             <id>repository.spring.milestone</id>             <name>Spring Milestone Repository</name>             <url>https://repo.spring.io/milestone</url>         </repository>     </repositories>      <dependencies>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-context</artifactId>             <version>6.0.0-M2</version>         </dependency>         <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-jdbc</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>         <dependency>             <groupId>org.mybatis</groupId>             <artifactId>mybatis-spring</artifactId>             <version>2.0.7</version>         </dependency>         <dependency>             <groupId>com.alibaba</groupId>             <artifactId>druid</artifactId>             <version>1.2.13</version>         </dependency>         <dependency>             <groupId>junit</groupId>             <artifactId>junit</artifactId>             <version>4.13.2</version>             <scope>test</scope>         </dependency>     </dependencies>  </project> 
  1. 第三步:基于三层架构实现,所以提前创建好所有的包
      • com.powernode.bank.mapper
      • com.powernode.bank.service
      • com.powernode.bank.service.impl
      • com.powernode.bank.pojo

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)
Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

  1. 第四步:编写pojo
  • Account,属性私有化,提供公开的setter getter和toString。

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

  1. 第五步:编写mapper接口
  • AccountMapper接口,定义方法

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

package com.rainbowsea.bank.mapper;  import com.rainbowsea.bank.pojo.Account;  import java.util.List;  // 该接口的实现类不需要写,是mybatis通过动态代理机制生成的实现类 public interface AccountMapper {      // 这就是DAO,只要编写CRUD方法即可      /**      * 新增账户      * @param account      * @return      */     int insert(Account account);       /**      * 根据账户删除账户      * @param actno      * @return      */     int deleteByActno(String actno);       /**      * 根据账户更新      * @param account      * @return      */     int update(Account account);       /**      * 根据账户查询账户      * @param actno      * @return      */     Account selectByActno(String actno);       /**      * 查询所有的账户      * @return      */     List<Account> selectAll();  }  
  1. 第六步:编写mapper配置文件
  • 在配置文件中配置命名空间,以及每一个方法对应的sql。

一定要注意,按照下图提示创建这个目录。注意是 斜杠(因为是创建目录) 不是点儿。在resources目录下新建。并且要和Mapper接口包对应上。因为只有这样,MyBatis 才会进行动态代理这个接口。

同时:如果接口叫做AccountMapper,配置文件必须是 AccountMapper.xml,名称要保持一致。

总结两点:就是路径位置要保持一致,对应的名称也要保持一致。后缀名不同。

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

同时在 AccountMapper.xml 当中编写 SQL 语句内容。

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

<?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="com.rainbowsea.bank.mapper.AccountMapper">      <insert id="insert">         insert into t_act(actno,balance) values(#{actno}, #{balance})     </insert>      <delete id="deleteByActno">         delete from t_act where actno = #{actno}     </delete>      <update id="update">         update t_act set balance = #{balance} where actno = #{actno}     </update>      <select id="selectByActno" resultType="Account">         select * from t_act where actno = #{actno}     </select>      <select id="selectAll" resultType="Account">         select * from t_act     </select> </mapper> 
  1. 第七步:编写service接口和service接口实现类
      • AccountService
      • AccountServiceImpl

编写 AccountService 业务接口,定义约束,规范,进行一个业务上的转账操作。

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

package com.rainbowsea.bank.service;  import com.rainbowsea.bank.pojo.Account; import org.springframework.transaction.annotation.Transactional;  import java.util.List;   public interface AccountService {     /**      * 开户      * @param account      * @return      */     int save(Account account);      /**      * 根据账号销户      * @param actno      * @return      */     int deleteByActno(String actno);      /**      * 修改账户      * @param act      * @return      */     int update(Account act);      /**      * 根据账号获取账户      * @param actno      * @return      */     Account getByActno(String actno);      /**      * 获取所有账户      * @return      */     List<Account> getAll();      /**      * 转账      * @param fromActno      * @param toActno      * @param money      */     void transfer(String fromActno, String toActno, double money); }  

注意:要将编写的service实现类纳入IoC容器管理,同时注意需要开启事务@Transactional

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

package com.rainbowsea.bank.service.impl;  import com.rainbowsea.bank.mapper.AccountMapper; import com.rainbowsea.bank.pojo.Account; import com.rainbowsea.bank.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;  import java.util.List;  @Service(value = "accountServiceImpl") @Transactional  // 放在类中,下面的类中的所有方法都开启了事务 public class AccountServiceImpl implements AccountService {      // Could not find bean with name 'org.mybatis.spring.SqlSessionFactoryBean#0     @Autowired // 非简单类型自动装配     private AccountMapper accountMapper;     @Override     public int save(Account account) {         return accountMapper.insert(account);     }      @Override     public int deleteByActno(String actno) {         return accountMapper.deleteByActno(actno);     }      @Override     public int update(Account act) {         return accountMapper.update(act);     }      @Override     public Account getByActno(String actno) {         return accountMapper.selectByActno(actno);     }      @Override     public List<Account> getAll() {         return accountMapper.selectAll();     }      @Override     public void transfer(String fromActno, String toActno, double money) {         Account fromAct = accountMapper.selectByActno(fromActno);          if(fromAct.getBalance() < money) {             throw new RuntimeException("余额不足");         }          Account toAct = accountMapper.selectByActno(toActno);          //模拟异常       /*  String s = null;         s.toString(); */         // 内存上修改         fromAct.setBalance(fromAct.getBalance() - money);         toAct.setBalance(toAct.getBalance() + money);          // 数据库上修改数据内容         int count = accountMapper.update(fromAct);         count += accountMapper.update(toAct);          if(count != 2) {             throw new RuntimeException("转账失败");         }       } }  
  1. 第八步:在 resources 的根路径下,编写jdbc.properties配置文件
  • 数据库连接池相关信息,账号,密码,同时注意要加上 jdbc, 同时注意不要加任何的空格,同时是 放在类的根路径(resources )下

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring6 jdbc.username=root jdbc.password=MySQL123 
  1. 第九步:编写mybatis-config.xml配置文件
      • 该文件可以没有,大部分的配置可以转移到spring配置文件中。
      • 如果遇到mybatis相关的系统级配置,还是需要这个文件。
      • 放在类的根路径(resources )下,只开启日志,其他配置到spring.xml中。

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)
)

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"         "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--    帮助我们打印mybatis的日志信息。sql语句等-->     <settings>         <setting name="logImpl" value="STDOUT_LOGGING"/>     </settings>  </configuration> 
  1. 第十步:编写spring.xml配置文件
      • 组件扫描
      • 引入外部的属性文件
      • 数据源
      • SqlSessionFactoryBean配置
        • 注入mybatis核心配置文件路径
        • 指定别名包
        • 注入数据源
      • Mapper扫描配置器
        • 指定扫描的包
      • 事务管理器DataSourceTransactionManager
        • 注入数据源
      • 启用事务注解
        • 注入事务管理器
      • 同样,我们还是将其防止到 类的根路径下(resources )

注意:当你在spring.xml文件中直接写标签内容时,IDEA会自动给你添加命名空间

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

<?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">      <!--    组件扫描,-->     <context:component-scan base-package="com.rainbowsea.bank"></context:component-scan>          <!--    引入外部的属性配置文件-->      <context:property-placeholder location="jdbc.properties"></context:property-placeholder>      <!--    数据源-->     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">         <property name="driverClassName" value="${jdbc.driver}"></property>         <property name="url" value="${jdbc.url}"></property>         <property name="username" value="${jdbc.username}"></property>         <property name="password" value="${jdbc.password}"></property>     </bean>      <!--    配置SqlSessionFactoryBean  "org.mybatis.spring.SqlSessionFactoryBean"-->     <bean class="org.mybatis.spring.SqlSessionFactoryBean">         <!--        注入数据源-->         <property name="dataSource" ref="dataSource"></property>         <!--        指定mybatis 核心配置文件-->         <property name="configLocation" value="mybatis-config.xml"></property>         <!--        指定别名-->         <property name="typeAliasesPackage" value="com.rainbowsea.bank.pojo"></property>      </bean>      <!--    Mapper 扫描配置器,主要扫描Mapper 接口,生成代理类-->     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">         <property name="basePackage" value="com.rainbowsea.bank.mapper"></property>     </bean>      <!--    事务管理器-->     <bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">         <!--        配置数据源-->         <property name="dataSource" ref="dataSource"></property>     </bean>      <!--    启用事务注解,事务管理器-->     <tx:annotation-driven transaction-manager="txManger"></tx:annotation-driven> </beans> 
  1. 第十一步:编写测试程序,并添加事务,进行测试

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)
)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

package com.rainbowsea.spring6.test;  import com.rainbowsea.bank.service.AccountService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;  public class SpringMybatisTest {      @Test     public void testSpringMybatis() {         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");         // AccountService.class 左右两边保持一致性         AccountService accountService = applicationContext.getBean("accountServiceImpl", AccountService.class);         try {             accountService.transfer("act-001","act-002",10000);             System.out.println("转账成功");         } catch (Exception e) {             throw new RuntimeException(e);         }      } }  

没有异常,看是否能转账成功

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

模拟异常,看是否,能够进行正常的事务回滚

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

运行测试:

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)


4. Spring配置文件的 import,导入外部xml 配置

如果 spring 配置文件有多个,可以在 spring 的核心配置文件中使用 import 进行引入,我们可以将组件扫描单独定义到一个配置文件中,如下:我们将一个《组件扫描》,定义到一个单独的名为common.xml的配置文件当中去,并导入,引入到 spring 的配置文件当中使用。如下:

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

使用<import> 标签进行一个导入

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

<!--    在Spring 的核心配置文件中引入其他的子 spring 配置文件-->     <import resource="common.xml"></import> 

把模拟异常去了,测试,是否能够转账成功。如下:

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

注意:在实际开发中,service 单独配置到一个文件中,dao单独配置到一个文件中,然后在核心配置文件中引入,养成好习惯。

5. 总结:

  1. Spring6 对集成MyBatis 开发:这里总的来说是十步,完成的。

  2. 一定要注意,按照下图提示创建这个目录。注意是 斜杠(因为是创建目录) 不是点儿。在resources目录下新建。并且要和Mapper接口包对应上。因为只有这样,MyBatis 才会进行动态代理这个接口。

    同时:如果接口叫做AccountMapper,配置文件必须是 AccountMapper.xml,名称要保持一致。

    总结两点:就是路径位置要保持一致,对应的名称也要保持一致。后缀名不同。

  3. Spring 当中使用<import> 标签导入外部xml 配置。

6. 最后:

“在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。”

Spring6 对 集成MyBatis 开发运用(附有详细的操作步骤)

发表评论

评论已关闭。

相关文章