MybatisPlus|整合SpringBoot

1. 基础知识介绍

1.1 MP概要

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

1.2 MP特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2. 环境准备

  • 操作系统:macOS Catalina 10.15.3
  • IDEA:IntelliJ IDEA 2019.1 (Ultimate Edition)
  • JDK:1.8
  • SpringBoot:2.3.1
  • MybatisPlus:3.3.2
  • Mysql:8.0.19

3. 项目结构

MybatisPlus|整合SpringBoot_第1张图片

4. 基本操作过程

4.1 创建测试表

CREATE DATABASE mp;
USE mp;

DROP TABLE IF EXISTS `tbl_employee`;

CREATE TABLE `tbl_employee` (
  `id` int NOT NULL AUTO_INCREMENT,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


LOCK TABLES `tbl_employee` WRITE;

INSERT INTO `tbl_employee` VALUES (1,'Tom','[email protected]','1',22),(2,'Hedon','Hedon@hedon,com','1',21),(3,'Jerry','[email protected]','2',18),(4,'White','[email protected]','2',30);

UNLOCK TABLES;

4.2 创建 SpringBoot 的 Web 项目

MybatisPlus|整合SpringBoot_第2张图片

4.3 编写 pom.xml 文件,加入依赖坐标

重点:

  • mybatis-plus
  • lombok
<dependency>
  <groupId>org.projectlombokgroupId>
  <artifactId>lombokartifactId>
  <optional>trueoptional>
dependency>
<dependency>
  <groupId>com.baomidougroupId>
  <artifactId>mybatis-plus-boot-starterartifactId>
  <version>3.3.2version>
dependency>

4.4 编写配置文件 application.properties,配置数据库连接信息

spring.application.name=itcast-mp-springboot

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp
spring.datasource.username=root
spring.datasource.password=root

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹

MybatisPlus|整合SpringBoot_第3张图片

4.6 编写实体类 Employee

package it.cast.mp.itcastmpspringboot.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author Hedon Wang
 * @create 2020-06-24 22:53
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName(value = "tbl_employee")
public class Employee {

    @TableId(value = "id",type = IdType.AUTO)
    private Integer id ;   //  int
    private String  lastName;
    private String  email ;
    private Integer gender;
    private Integer age ;
    private Double  salary ;

}

4.7 编写Mapper接口,并继承MP提供的BaseMapper

package it.cast.mp.itcastmpspringboot.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import it.cast.mp.itcastmpspringboot.pojo.Employee;

/**
 * @author Hedon Wang
 * @create 2020-06-25 00:25
 */
public interface EmployeeMapper extends BaseMapper<Employee> {

}

4.8 测试 selectList()

@RunWith(SpringRunner.class)
@SpringBootTest
class ItcastMpSpringbootApplicationTests {

    @Autowired
    EmployeeMapper employeeMapper;

    @Test
    public void testSearchList(){
        List<Employee> employees = employeeMapper.selectList(null);
        for (Employee employee:employees){
            System.out.println(employee);
        }
    }
}
  • 测试结果

MybatisPlus|整合SpringBoot_第4张图片

5. 项目源码

5.1 ItcastMpSpringbootApplication.java

package it.cast.mp.itcastmpspringboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@MapperScan("it.cast.mp.itcastmpspringboot.mapper")
@SpringBootApplication
public class ItcastMpSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(ItcastMpSpringbootApplication.class, args);
    }

}

5.2 Employee.java

package it.cast.mp.itcastmpspringboot.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author Hedon Wang
 * @create 2020-06-24 22:53
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName(value = "tbl_employee")
public class Employee {

    @TableId(value = "id",type = IdType.AUTO)
    private Integer id ;   //  int
    private String  lastName;
    private String  email ;
    private Integer gender;
    private Integer age ;
    private Double  salary ;

}

5.3 EmployeeMapper.java

package it.cast.mp.itcastmpspringboot.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import it.cast.mp.itcastmpspringboot.pojo.Employee;

/**
 * @author Hedon Wang
 * @create 2020-06-25 00:25
 */
public interface EmployeeMapper extends BaseMapper<Employee> {

}

5.4 application.properties

spring.application.name=itcast-mp-springboot

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp
spring.datasource.username=root
spring.datasource.password=root

5.5 log4j.properties

log4j.rootLogger=DEBUG,A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout = org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t]  [%c]-[%p]  %m%n

5.6 ItcastMpSpringbootApplicationTests.java

package it.cast.mp.itcastmpspringboot;

import it.cast.mp.itcastmpspringboot.mapper.EmployeeMapper;
import it.cast.mp.itcastmpspringboot.pojo.Employee;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
class ItcastMpSpringbootApplicationTests {


    @Autowired
    EmployeeMapper employeeMapper;

    @Test
    void contextLoads() {
    }


    @Test
    public void testSearchList(){
        List<Employee> employees = employeeMapper.selectList(null);
        for (Employee employee:employees){
            System.out.println(employee);
        }
    }

}

5.7 pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.1.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>it.cast.mpgroupId>
    <artifactId>itcast-mp-springbootartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>itcast-mp-springbootname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starterartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.3.2version>
            dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

你可能感兴趣的:(Java学习,MybatisPlus)