当前流行的框架之SpringBoot整合MyBatis

SpringBoot作为当前Java中最流行生态Spring家族中的一员,已经是当前的趋势。将开发人员从SSM中的配置地狱中解放出来,那么相对于SSM,SpringBoot如何整合进MyBatis呢?一起来看看吧~

环境搭建

SpringBoot整合MyBatis可以采用三种方式:

  1. 注解版
  2. 配置文件版
  3. 注解+配置文件

创建SpringBoot项目与整合JDBC一致,使用Druid数据源。pom.xml加入MyBatis依赖。

xml 复制代码
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

配置数据库连接信息,使用Druid数据源,与其不变。

yml 复制代码
spring:
  datasource:
    username: root
    password: kylin
    # 假如时区报错了,就增加一个时区的配置
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
​
​
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
​
    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

给数据库建表,导入department.sql和employee.sql。SpringBoot连接数据库之后自动建表。首先需要再SpringBoot文件中配置两张建表sql的位置

SpringBoot2.0x版本自动运行建表sql,必须配置参数initialization-mode: always

运行项目后,就会自动运行Sql语句。进行建表操作

为了每次运行此项目都自动运行建表语句,我们把他给注释掉

创建相对应的JavaBean

注解版

使用MyBatis注解来进行对数据库的操作

由于没有Mybatis的配置文件。而数据库表中的d_id,department_name字段与bean中不一致。所以需要配置mybatis自动驼峰命名转换。

自定义MyBatis的配置规则,给容器中添加一个ConfigurationCustomizer。相当于mybatis.xml配置文件

configuration.setMapUnderscoreToCamelCase(true);开启自动驼峰命名转换

java 复制代码
@Configuration
public class MyBatisConfig {
​
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                //开启自动驼峰命名转换 department_name
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

编写controller

测试插入

由于id是自增主键,我们插入时是没有Id的值。/dept?departmentName=xx所以获取到的department对象中的Id时null,而在数据库中id自增。

这时我们可以在Mapper中使用@Options注解@Options(useGeneratedKeys =true,keyProperty = "id")插入完成后,主键会重新封装进来。

再次测试插入

测试通过Id获取对象

通过注解版整合Mybatis成功!!

配置文件版

首先在SpringBoot配置文件中配置mybatis和mapper配置文件所在位置。

mybatis配置文件

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>
        <!--开启驼峰命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.kylin.bean"/>
    </typeAliases>
</configuration>

创建Mapper接口

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="com.kylin.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="employee">
        select * from employee where id = #{id}
    </select>
​
    <insert id="insertEmp">
        insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

编写Mapper.xml

编写Controller

测试插入

与上面一样的原因,导致id为null。我们在mapper配置文件中配置属性userGeneratedKeys="true"keyProperty="id"

测试查询

通过配置文件版整合Mybatis成功!!

两种方式可以混合使用!!

相关推荐
追逐时光者5 小时前
推荐 12 款开源美观、简单易用的 WPF UI 控件库,让 WPF 应用界面焕然一新!
后端·.net
Jagger_5 小时前
敏捷开发流程-精简版
前端·后端
苏打水com6 小时前
数据库进阶实战:从性能优化到分布式架构的核心突破
数据库·后端
间彧7 小时前
Spring Cloud Gateway与Kong或Nginx等API网关相比有哪些优劣势?
后端
间彧7 小时前
如何基于Spring Cloud Gateway实现灰度发布的具体配置示例?
后端
间彧7 小时前
在实际项目中如何设计一个高可用的Spring Cloud Gateway集群?
后端
间彧7 小时前
如何为Spring Cloud Gateway配置具体的负载均衡策略?
后端
间彧7 小时前
Spring Cloud Gateway详解与应用实战
后端
EnCi Zheng9 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端
烙印6019 小时前
Spring容器的心脏:深度解析refresh()方法(上)
java·后端·spring