SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)

1.整合mybatis

1.需求分析
2.数据库表设计
CREATE DATABASE `springboot_mybatis`;

use `springboot_mybatis`;

CREATE TABLE `monster` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `age` INT NOT NULL, 
 `birthday` DATE DEFAULT NULL, 
 `email` VARCHAR(255) DEFAULT NULL,
 `gender` char(1) DEFAULT NULL,
 `name` VARCHAR(255) DEFAULT NULL, 
 `salary` DOUBLE NOT NULL,
 PRIMARY KEY (`id`)
);

SELECT * FROM `monster`;

insert into monster values(null, 20, '2000-11-11', 'nmw@sohu.***', '男', '牛魔王', 5000.88);
insert into monster values(null, 10, '2011-11-11', 'bgj@sohu.***', '女', '白骨精', 2000.00);
3.数据库环境配置
1.新建maven项目
2.pom.xml 引入依赖
    <!--导入springboot父工程-->
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.5.3</version>
    </parent>

    <!--引入相关依赖-->
    <dependencies>
        <!--常规依赖-->
        <!--web场景启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--引入测试场景启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--配置处理器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!--数据库配置-->
        <!--引入data-jdbc数据源-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <!--mysql依赖使用版本仲裁-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- 引入 druid 依赖 -->
        <dependency>
            <groupId>***.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!--MyBatis场景启动器-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>
3.application.yml 配置数据源
  • 数据库名
  • 用户名
  • 密码
  • 驱动是mysql8的(因为上面使用了版本仲裁)
server:
  port: 8080
spring:
  datasource: #配置数据源
    url: jdbc:mysql://localhost:3306/springboot_mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: ***.mysql.cj.jdbc.Driver
4.Application.java 编写启动类
package ***.sun.springboot.mybatis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

5.测试
package ***.sun.springboot.mybatis;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootTest
public class ApplicationTest {
    //依赖注入
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Test
    public void t1() {
        //查看目前数据源
        System.out.println(jdbcTemplate.getDataSource().getClass());
    }
}

6.配置类切换druid数据源
package ***.sun.springboot.mybatis.config;

import ***.alibaba.druid.pool.DruidDataSource;
import ***.alibaba.druid.support.http.StatViewServlet;
import ***.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Configuration
public class DruidDataSourceConfig {

    //注入一个德鲁伊数据源
    @ConfigurationProperties("spring.datasource") //读取yaml配置文件的参数,获取数据源配置
    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setFilters("stat, wall"); //开启sql监控
        return druidDataSource;
    }

    //配置德鲁伊监控sql功能
    @Bean
    public ServletRegistrationBean statViewServlet() {
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean =
                new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        //配置登录监控页面用户名和密码
        registrationBean.addInitParameter("loginUsername", "root");
        registrationBean.addInitParameter("loginPassword", "root");
        return registrationBean;
    }

    //配置webStatFilter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean =
                new FilterRegistrationBean<>(webStatFilter);
        //默认对所有 URL 请求监控
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        //排除 URL
        filterRegistrationBean.addInitParameter
                ("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
7.测试数据源是否成功切换
package ***.sun.springboot.mybatis;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootTest
public class ApplicationTest {
    //依赖注入
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Test
    public void t1() {
        //查看目前数据源
        System.out.println(jdbcTemplate.getDataSource().getClass());
    }
}
4.Mybatis基础配置
1.编写映射表的bean
package ***.sun.springboot.mybatis.bean;

import ***.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.util.Date;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Data
public class Monster {
    private Integer id;
    private Integer age;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date birthday;
    private String email;
    private String name;
    private String gender;
    private Double salary;
}

2.MonsterMapper.java 编写mapper接口
  • 使用注解注入容器
package ***.sun.springboot.mybatis.mapper;

import ***.sun.springboot.mybatis.bean.Monster;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Mapper //将接口注入容器
public interface MonsterMapper {
    public Monster getMonsterById(Integer id);
}

3.MonsterMapper.xml 编写mapper.xml实现mapper接口
  • 使用namespace指定要实现的接口
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--指定要实现的接口-->
<mapper namespace="***.sun.springboot.mybatis.mapper.MonsterMapper">
    <select id="getMonsterById" resultType="***.sun.springboot.mybatis.bean.Monster" parameterType="Integer">
        select * from monster where id = #{id}
    </select>
</mapper>
4.application.yml 扫描mapper.xml配置文件的位置
  • 扫描类路径下mapper文件夹下的所有文件
mybatis:
  #指定要扫描的mapper.xml
  mapper-locations: classpath:mapper/*.xml
5.测试
package ***.sun.springboot.mybatis;

import ***.sun.springboot.mybatis.bean.Monster;
import ***.sun.springboot.mybatis.mapper.MonsterMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootTest
public class ApplicationTest {
    //依赖注入
    @Resource
    private JdbcTemplate jdbcTemplate;
    //注意这里注入的是MonsterMapper的代理对象
    @Resource
    private MonsterMapper monsterMapper;

    @Test
    public void t1() {
        //查看目前数据源
        System.out.println(jdbcTemplate.getDataSource().getClass());
    }

    @Test
    public void t2() {
        //测试mybatis
        Monster monsterById = monsterMapper.getMonsterById(1);
        System.out.println(monsterById);
    }
}

5.MyBatis高级配置
1.方式一:在application.yml中配置mybatis.config-location指定mybatis-config.xml配置文件的位置
2.方式二:直接在application.yml中配置
mybatis:
  #指定要扫描的mapper.xml
  mapper-locations: classpath:mapper/*.xml
  #配置类型别名包,这样只要在这个包下的类型都可以简写
  type-aliases-package: ***/sun/springboot/mybatis/bean
  #输出日志
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6.继续编写Service层和Controller层
1.MonsterService.java
package ***.sun.springboot.mybatis.service;

import ***.sun.springboot.mybatis.bean.Monster;

/**
 * @author 孙显圣
 * @version 1.0
 */
public interface MonsterService {
    public Monster getMonsterById(Integer id);
}

2.MonsterServiceImpl.java
package ***.sun.springboot.mybatis.service.Impl;

import ***.sun.springboot.mybatis.bean.Monster;
import ***.sun.springboot.mybatis.mapper.MonsterMapper;
import ***.sun.springboot.mybatis.service.MonsterService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Service
public class MonsterServiceImpl implements MonsterService {
    @Resource
    private MonsterMapper monsterMapper; //返回代理对象
    @Override
    public Monster getMonsterById(Integer id) {
        return monsterMapper.getMonsterById(id);
    }
}
3.测试
package ***.sun.springboot.mybatis;

import ***.sun.springboot.mybatis.bean.Monster;
import ***.sun.springboot.mybatis.mapper.MonsterMapper;
import ***.sun.springboot.mybatis.service.MonsterService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootTest
public class ApplicationTest {
    //依赖注入
    @Resource
    private MonsterService monsterService;

    @Test
    public void getMonsterById() {
        Monster monsterById = monsterService.getMonsterById(1);
        System.out.println(monsterById);
    }
}

4.MonsterController.java
package ***.sun.springboot.mybatis.Controller;

import ***.sun.springboot.mybatis.bean.Monster;
import ***.sun.springboot.mybatis.service.MonsterService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Controller
public class MonsterController {
    @Resource
    private MonsterService monsterService;

    @GetMapping("/getMonster/{id}") //路径参数的请求
    @ResponseBody //响应一个json
    public Monster getMonsterById(@PathVariable("id") Integer id) {
        Monster monsterById = monsterService.getMonsterById(id);
        return monsterById;
    }
}

5.测试
6.解决时间问题
7.完整文件目录

2.整合MyBatis-Plus

1.MyBatis-Plus基本介绍
2.数据库表设计
CREATE DATABASE `springboot_mybatisplus`;

USE `springboot_mybatisplus`;

CREATE TABLE `monster` (
`id` INT NOT NULL AUTO_INCREMENT,
`age` INT NOT NULL, 
`birthday` DATE DEFAULT NULL, 
`email` VARCHAR(255) DEFAULT NULL, 
`gender` CHAR(1) DEFAULT NULL, 
`name` VARCHAR(255) DEFAULT NULL, 
`salary` DOUBLE NOT NULL,
PRIMARY KEY (`id`)
);
SELECT * FROM `monster`;
INSERT INTO monster VALUES(NULL, 20, '2000-11-11', 'xzj@sohu.***', '男', ' 蝎 子 精 ',
15000.88);
INSERT INTO monster VALUES(NULL, 10, '2011-11-11', 'ytj@sohu.***', '女', ' 玉 兔 精 ',
18000.88);
3.数据库环境配置
1.创建maven项目
2.pom.xml 导入依赖
  <!--导入springboot父工程-->
  <parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.5.3</version>
  </parent>

  <!--引入相关依赖-->
  <dependencies>
    <!--常规依赖-->
    <!--web场景启动器-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <!--引入测试场景启动器-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--配置处理器-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </dependency>

    <!--数据库配置-->
    <!--mysql依赖使用版本仲裁-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <!-- 引入 druid 依赖 -->
    <dependency>
      <groupId>***.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.17</version>
    </dependency>
    
    <!--引入MyBatis-Plus场景启动器,会自动引入jdbc和MyBatis-->
    <dependency>
      <groupId>***.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.4.3</version>
    </dependency>
  </dependencies>
3.application.yml 配置数据源
  • 数据库名称
  • 用户名
  • 密码
server:
  port: 8080
spring:
  datasource:
    driver-class-name: ***.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_mybatisplus?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root

4.DruidDataSourceConfig.java 配置类切换druid数据源
package ***.sun.springboot.mybatisplus.config;

import ***.alibaba.druid.pool.DruidDataSource;
import ***.alibaba.druid.support.http.StatViewServlet;
import ***.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Configuration
public class DruidDataSourceConfig {

    //注入一个德鲁伊数据源
    @ConfigurationProperties("spring.datasource") //读取yaml配置文件的参数,获取数据源配置
    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setFilters("stat, wall"); //开启sql监控
        return druidDataSource;
    }

    //配置德鲁伊监控sql功能
    @Bean
    public ServletRegistrationBean statViewServlet() {
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean =
                new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        //配置登录监控页面用户名和密码
        registrationBean.addInitParameter("loginUsername", "root");
        registrationBean.addInitParameter("loginPassword", "root");
        return registrationBean;
    }

    //配置webStatFilter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean =
                new FilterRegistrationBean<>(webStatFilter);
        //默认对所有 URL 请求监控
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        //排除 URL
        filterRegistrationBean.addInitParameter
                ("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
5.编写启动类Application.java,测试运行
package ***.sun.springboot.mybatisplus;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4.MyBatis-Plus基础配置
1.编写映射表的bean
package ***.sun.springboot.mybatisplus.bean;

import ***.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.util.Date;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Data
public class Monster {
    private Integer id;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date birthday;
    private String email;
    private String name;
    private String gender;
    private Double salary;
}
2.MonsterMapper.java 编写Mapper接口
package ***.sun.springboot.mybatisplus.mapper;

import ***.baomidou.mybatisplus.core.mapper.BaseMapper;
import ***.sun.springboot.mybatisplus.bean.Monster;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author 孙显圣
 * @version 1.0
 */
//直接继承BaseMapper接口
@Mapper //注入容器
public interface MonsterMapper extends BaseMapper<Monster> {
    //如果提供的方法不够用再自定义方法
}

3.测试接口方法使用
package ***.sun.springboot.mybatisplus;

import ***.sun.springboot.mybatisplus.bean.Monster;
import ***.sun.springboot.mybatisplus.mapper.MonsterMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootTest
public class MonsterMapperTest {
    //注入针对Mapper接口的代理对象
    @Resource
    private MonsterMapper monsterMapper;
    @Test
    public void t1() {
        Monster monster = monsterMapper.selectById(1);
        System.out.println(monster);
    }
}

5.MyBatis-Plus高级配置
application.yml 进行配置
#进行mybatis-plus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6.继续编写Service层和Controller层
1.MonsterService.java
package ***.sun.springboot.mybatisplus.service.Impl;

import ***.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ***.sun.springboot.mybatisplus.bean.Monster;
import ***.sun.springboot.mybatisplus.mapper.MonsterMapper;
import ***.sun.springboot.mybatisplus.service.MonsterService;
import org.springframework.stereotype.Service;

/**
 * 这里
 * @author 孙显圣
 * @version 1.0
 */
@Service
public class MonsterServiceImpl extends ServiceImpl<MonsterMapper, Monster> implements MonsterService {
    //自定义方法实现
}

2.MonsterServiceImpl.java
package ***.sun.springboot.mybatisplus.service.Impl;

import ***.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ***.sun.springboot.mybatisplus.bean.Monster;
import ***.sun.springboot.mybatisplus.mapper.MonsterMapper;
import ***.sun.springboot.mybatisplus.service.MonsterService;
import org.springframework.stereotype.Service;

/**
 * 这里
 * @author 孙显圣
 * @version 1.0
 */
@Service
public class MonsterServiceImpl extends ServiceImpl<MonsterMapper, Monster> implements MonsterService {
    //自定义方法实现
}

3.测试
package ***.sun.springboot.mybatisplus;

import ***.sun.springboot.mybatisplus.bean.Monster;
import ***.sun.springboot.mybatisplus.mapper.MonsterMapper;
import ***.sun.springboot.mybatisplus.service.MonsterService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@SpringBootTest
public class MonsterServiceTest {
    @Resource
    private MonsterService monsterService;
    @Test
    public void t1() {
        Monster byId = monsterService.getById(2);
        System.out.println(byId);
    }
}

4.细节说明
  • 简单来说就是MonsterServiceImpl只需要实现MonsterService接口的方法
  • 可以调用IService接口的方法,也可以调用MonsterService接口的方法
5.MonsterController.java
package ***.sun.springboot.mybatisplus.controller;

import ***.sun.springboot.mybatisplus.bean.Monster;
import ***.sun.springboot.mybatisplus.service.MonsterService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Controller
public class MonsterController {
    @Resource
    //注入的是MonsterServiceImpl的bean对象,可以直接调用IService接口的方法
    private MonsterService monsterService;
    @GetMapping("/getMonster/{id}")
    @ResponseBody
    public Monster getMonsterById(@PathVariable("id") Integer id) {
        Monster byId = monsterService.getById(id);
        return byId;
    }
}

7.细节说明
1.@MapperScan 扫描包下的所有Mapper
启动类配置注解
2.@TableName bean的类名与表名不一致时使用
3.MyBatis引入了哪些依赖
8.MyBatisX快速开发
1.安装插件
2.使用方式
1.挑一个带小鸟的方法
2.直接alt + Enter
3.生成sql语句
4.查看生成的方法
5.点击左边的小鸟就可以直接跳转到指定方法或者xml
9.完整文件目录
10.MyBatis-Plus小结
转载请说明出处内容投诉
CSS教程_站长资源网 » SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买