SSMSpring集成Mybatis

Posted 假正经的小柴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSMSpring集成Mybatis相关的知识,希望对你有一定的参考价值。

Spring框架集成Mybtis

为啥学习集成 Mybatis ORM 框架

虽然Spring中提供了JDBCTemplate模块,已经很大程度了解决了JDBC代码的复杂度,但它仍然是和Java代码写在一起的。反观 Mybatis 将 Sql 语句写在配置文件中,使得SQL语句和程序实现了松耦合。而且提供了些许标签,使得SQL可以是动态的。在ORM基础上想要更好的用Spring的DI、AOP、事务处理、Junit支持等实现成果,学会使用 Spring 框架集成 Mybatis 是大势所趋。

实现步骤

  • 第一步:准备数据库表

  • 第二步:IDEA中创建一个模块,并引入以下依赖
  1. spring-context
  2. spring-jdbc
  3. mysql驱动
  4. mybatis
  5. mybatis-spring:mybatis提供的与spring框架集成的依赖
  6. druid:德鲁伊连接池
  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>
  • 第三步:基于三层架构实现,所以提前创建好所有的包
  1. XXXX.mapper
  2. XXXX.service
  3. XXXX.service.impl
  4. XXXX.bean

  • 第四步:编写bean
    Account,按bean规范创建

  • 第五步:编写Mapper接口
    AccountMapper接口,定义与数据库交互的方法
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);


  • 第六步:编写mapper配置文件
<?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>
  • 第七步:编写service接口和service接口的实现类

service接口

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实现

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("转账失败");
    


  • 第八步:编写jdbc.properties配置文件
    数据库连接池相关信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
  • 第九步:编写mybatis-config.xml核心配置文件
<?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>
  • 第十步:编写spring.xml配置文件
    组件扫描
    引入外部的属性文件
    数据源
    SqlSessionFactoryBean配置(注入mybatis核心配置文件路径,指明别名包,注入数据源)
    Mapper扫描配置器(指定扫描的包)
    事务管理器(DataSourceTransactionManager,注入数据源)
    启动事务注解(注入事务管理器)
<?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>
  • 第十一步:编写测试程序,并添加事务,进行测试。
	@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);
    

测试结果

以上是关于SSMSpring集成Mybatis的主要内容,如果未能解决你的问题,请参考以下文章

专注Java相关技术:SSMSpring全家桶微服务MySQL集群dubbo分布式中间件Linux网络多线程JenkinsNexusDockerELK等等!

Spring Boot

mybatismybatis资料

mybatisMyBatis Generator

MybatisMyBatis 注解方式的基本 用法

MybatisMyBatis之缓存