[SSM] Spring integrates Mybatis

Why learn to integrate Mybatis ORM framework

Although the JDBCTemplate module is provided in Spring, which has largely solved the complexity of the JDBC code, it is still written together with the Java code. In contrast, Mybatis writes Sql statements in the configuration file, making SQL statements and programs loosely coupled. Moreover, some tags are provided so that SQL can be dynamic. On the basis of ORM, if you want to better use Spring's DI, AOP, transaction processing, Junit support, etc. to achieve results, learning to use the Spring framework to integrate Mybatis is the general trend.

Implementation steps

  • Step 1: Prepare the database tables

insert image description here

  • Step 2: Create a module in IDEA and introduce the following dependencies
  1. spring-context
  2. spring-jdbc
  3. mysql driver
  4. my shoe
  5. mybatis-spring: mybatis提供的Dependency integrated with spring framework
  6. druid: Druid connection pool
  7. junit
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</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>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • Step 3: Realize based on the three-tier architecture, so create all packages in advance
  1. XXXX.mapper
  2. XXXX.service
  3. XXXX.service.impl
  4. XXXX.bean

insert image description here

  • Step 4: Write the bean
    Account and create it according to the bean specification

insert image description here

  • Step 5: Write the Mapper interface
    AccountMapper interface to define the method of interacting with the database
package com.ncpowernode.spring.mappers;

import com.ncpowernode.spring.bean.Account;

import java.util.List;

public interface AccountMapper {
    
    

    List<Account> selectAll();
    
    Account selectByActno(String actno);

    int insert(Account account);

    int deleteByActno(String actno);

    int update(Account account);
}

  • Step 6: Write mapper configuration file
<?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.ncpowernode.spring.mappers.AccountMapper">

    <select id="selectAll" resultType="account">
        select * from t_act;
    </select>

    <insert id="insert">
        insert into t_act values(#{actno},#{balance})
    </insert>

    <delete id="deleteByActno">
        delete from t_act where actno = #{actno};
    </delete>

    <select id="selectByActno" resultType="account">
        select * from t_act where actno = #{actno};
    </select>

    <update id="update">
        update t_act set balance = #{balance} where actno = #{actno};
    </update>

</mapper>
  • Step 7: Write the service interface and the implementation class of the service interface

service interface

package com.ncpowernode.spring.service;

import com.ncpowernode.spring.bean.Account;

import java.util.List;

public interface AccountService {
    
    

    int save(Account act);

    int deleteByActno(String actno);

    List<Account> getAll();

    void transfer(String fromActno,String toActno,double money);

}

service implementation

package com.ncpowernode.spring.service.impl;

import com.ncpowernode.spring.bean.Account;
import com.ncpowernode.spring.mappers.AccountMapper;
import com.ncpowernode.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
    
    

    @Autowired
    @Qualifier("accountMapper")
    private AccountMapper accountMapper;

    @Override
    public int save(Account act) {
    
    
        return accountMapper.insert(act);
    }

    @Override
    public int deleteByActno(String actno) {
    
    
        return accountMapper.deleteByActno(actno);
    }

    @Override
    public List<Account> getAll() {
    
    
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromActno, String toActno, double money) {
    
    
        // 判断余额
        Account fromAccount = accountMapper.selectByActno(fromActno);
        if (fromAccount.getBalance()<money) throw new RuntimeException("余额不足");
        // 更新数据库
        Account toAccount = accountMapper.selectByActno(toActno);
        fromAccount.setBalance(fromAccount.getBalance()-money);
        toAccount.setBalance(toAccount.getBalance()+money);
        int cnt = accountMapper.update(fromAccount);
        cnt += accountMapper.update(toAccount);
        // 判断业务是否实现成功
        if(cnt!=2) throw new RuntimeException("转账失败");
    }
}

  • Step 8: Write jdbc.properties configuration file
    database connection pool related information
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
  • Step 9: Write the mybatis-config.xml core configuration file
<?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>

    <settings>
        <!--驼峰命名自动映射,默认false-->
        <setting name="mapUnderscoreToCamelCase" value="false"/>
        <!--设置懒加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--配置日志,可以帮助我们查看sql执行信息-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

</configuration>
  • Step 10: Write spring.xml configuration file
    Component scanning
    Import external property files
    Data source
    SqlSessionFactoryBean configuration (inject mybatis core configuration file path, specify alias package, inject data source)
    Mapper scan configurator (specify scanned package)
    transaction manager (DataSourceTransactionManager, inject data source)
    start transaction annotation (inject transaction manager)
<?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">

    <!--组件扫描-->
    <context:component-scan base-package="com.ncpowernode.spring.service"/>
    <!--引入外部的属性文件-->
    <context:property-placeholder location="jdbc.properties"/>
    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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="com.ncpowernode.spring.bean"/>
        <!--指定mybatis核心配置文件-->
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>
    
    <!--配置Mapper扫描配置器-->
    <!--主要扫描mapper接口,生成代理类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ncpowernode.spring.mappers"/>
    </bean>
    
    <!--事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--启动事务注解-->
    <tx:annotation-driven transaction-manager="txManager"/>
    

</beans>
  • Step 11: Write a test program, add transactions, and test.
	@Test
    public void testSM(){
    
    
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccountService accountService = applicationContext.getBean("accountService", AccountServiceImpl.class);
        accountService.getAll().forEach(System.out::println);
        accountService.transfer("act-001","act-002",10000.0);
    }

Test Results

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/qq_63691275/article/details/129474765