专栏名称: 西界__
目录
今天看啥  ›  专栏  ›  西界__

SpringBoot整合MyBatis

西界__  · 简书  ·  · 2021-01-15 11:24

文章预览

环境搭建

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

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

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); 开启自动驼峰命名转换

@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 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 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成功!!

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

………………………………

原文地址:访问原文地址
快照地址: 访问文章快照
总结与预览地址:访问总结与预览