MybatisPlus概述及使用

文章目录

  • MybatisPlus
    • 1、介绍
      • 1.1、概述
      • 1.2、特性
      • 1.3、 支持数据库
      • 1.4、框架结构
    • 2、起步依赖与核心接口
      • 2.1 起步依赖
      • 2.2 BaseMapper
    • 3、快速入门
      • 3.1、导入依赖
      • 3.2、SpringBoot配置文件
      • 3.3、实体类
      • 3.4、Mapper接口
      • 3.5、引导类增加MapperScan注解
      • 3.6 测试
    • 4、注解
      • 4.1 @TableName
      • 4.2 @TableId
      • 4.3 @TableField
    • 5、常用API
      • 5.1 增加
      • 5.2 删除
      • 5.3 修改
      • 5.4 查询
      • 5.5 分页插件【了解】
    • 6.在Service层实现增强
    • 7、自定义Mapper

MybatisPlus

1、介绍

1.1、概述

  • 官网:
  • 是由国人开发一款Mybatis的插件
  • 简称 MP,是一个 MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。
  • 愿景:成为 MyBatis 最好的搭档
  • 源码:https://gitee.com/baomidou/mybatis-plus

1.2、特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

1.3、 支持数据库

  • MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb

1.4、框架结构

框架结构
MybatisPlus概述及使用_第1张图片

2、起步依赖与核心接口

2.1 起步依赖

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.1.1version>
dependency>

2.2 BaseMapper

  • Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
/*
 * Copyright (c) 2011-2020, baomidou ([email protected]).
 * 

* Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at *

* https://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.core.mapper; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Constants; import org.apache.ibatis.annotations.Param; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; /* :` .:, :::,,. :: `:::::: ::` `,:,` .:` `:: `::::::::.:` `:';,` ::::, .:::` `@++++++++: `` :::` @+++++++++++# :::, #++++++++++++++` ,: `::::::;'##++++++++++ .@#@;` ::::::::::::::::::::; #@####@, :::::::::::::::+#;::. @@######+@:::::::::::::. #@:; , @@########':::::::::::: .#''':` ;##@@@+:##########@::::::::::: @#;.,:. #@@@######++++#####'::::::::: .##+,:#` @@@@@#####+++++'#####+::::::::` ,`::@#:` `@@@@#####++++++'#####+#':::::::::::@. @@@@######+++++''#######+##';::::;':,` @@@@#####+++++'''#######++++++++++` #@@#####++++++''########++++++++' `#@######+++++''+########+++++++; `@@#####+++++''##########++++++, @@######+++++'##########+++++#` @@@@#####+++++############++++; ;#@@@@@####++++##############+++, @@@@@@@@@@@###@###############++' @#@@@@@@@@@@@@###################+: `@#@@@@@@@@@@@@@@###################'` :@#@@@@@@@@@@@@@@@@@##################, ,@@@@@@@@@@@@@@@@@@@@################; ,#@@@@@@@@@@@@@@@@@@@##############+` .#@@@@@@@@@@@@@@@@@@#############@, @@@@@@@@@@@@@@@@@@@###########@, :#@@@@@@@@@@@@@@@@##########@, `##@@@@@@@@@@@@@@@########+, `+@@@@@@@@@@@@@@@#####@:` `:@@@@@@@@@@@@@@##@;. `,'@@@@##@@@+;,` ``...`` _ _ /_ _ _/_. ____ / _ / / //_//_//_|/ /_\ /_///_/_\ Talk is cheap. Show me the code. _/ / */ /** * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能 *

这个 Mapper 支持 id 泛型

* * @author hubin * @since 2016-01-23 */
public interface BaseMapper<T> extends Mapper<T> { /** * 插入一条记录 * * @param entity 实体对象 */ int insert(T entity); /** * 根据 ID 删除 * * @param id 主键ID */ int deleteById(Serializable id); /** * 根据 columnMap 条件,删除记录 * * @param columnMap 表字段 map 对象 */ int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /** * 根据 entity 条件,删除记录 * * @param wrapper 实体对象封装操作类(可以为 null) */ int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper); /** * 删除(根据ID 批量删除) * * @param idList 主键ID列表(不能为 null 以及 empty) */ int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * 根据 ID 修改 * * @param entity 实体对象 */ int updateById(@Param(Constants.ENTITY) T entity); /** * 根据 whereEntity 条件,更新记录 * * @param entity 实体对象 (set 条件值,可以为 null) * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) */ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); /** * 根据 ID 查询 * * @param id 主键ID */ T selectById(Serializable id); /** * 查询(根据ID 批量查询) * * @param idList 主键ID列表(不能为 null 以及 empty) */ List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * 查询(根据 columnMap 条件) * * @param columnMap 表字段 map 对象 */ List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /** * 根据 entity 条件,查询一条记录 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询总记录数 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 entity 条件,查询全部记录 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录 * * @param queryWrapper 实体对象封装操作类(可以为 null) */ List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录 *

注意: 只返回第一个字段的值

* * @param queryWrapper 实体对象封装操作类(可以为 null) */
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 entity 条件,查询全部记录(并翻页) * * @param page 分页查询条件(可以为 RowBounds.DEFAULT) * @param queryWrapper 实体对象封装操作类(可以为 null) */ IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录(并翻页) * * @param page 分页查询条件 * @param queryWrapper 实体对象封装操作类 */ IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); }

3、快速入门

3.1、导入依赖

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
dependency>

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.1.1version>
dependency>
<dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelper-spring-boot-starterartifactId>
    <version>1.3.0version>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druid-spring-boot-starterartifactId>
    <version>1.1.10version>
dependency>

3.2、SpringBoot配置文件

logging:
  level:
    com.qf.java2108.demo04: debug

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/library?useSSL=false&serverTimezone=UTC&characterEncoding=UTF8&useUnicode=true
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource


mybatis-plus:
  type-aliases-package: com.qf.java2108.demo04.pojo
  mapper-locations: classpath:mapper/*Mapper.xml
  configuration:
    map-underscore-to-camel-case: true

3.3、实体类

package com.qf.java2108.demo04.pojo;

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

import java.util.Date;

/**
 * @author ghy
 * @version 1.0
 * @date
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
//映射数据库表,默认情况下,会把实体类名作为表名去映射
@TableName("tb_reader")
public class ReaderInfo {

    @TableId  //表示主键
    private Integer id;

    private String readerNum;
    private String readerName;

    //当数据库表的字段名跟Java实体属性名不一致,且也不满足驼峰命名时,必须使用@TableField来指定当前属性跟数据库表的哪个字段进行映射
    //@TableField("password")
    //private String pwd;

    private String password;
    private Integer gender;
    private Date birth;
    private String address;
    private String phone;
    private Date createTime;
    private Date updateTime;
    private Integer adminId;
    private Integer status;

}

3.4、Mapper接口

继承BaseMapper

public interface ReaderInfoMapper extends BaseMapper<ReaderInfo> {}

3.5、引导类增加MapperScan注解

@SpringBootApplication
@MapperScan("com.qf.java2108.demo04.mapper")
public class SpringBootDemo04Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo04Application.class, args);
    }
}

3.6 测试

package com.qf.java2108.demo04;

import com.qf.java2108.demo04.mapper.ReaderInfoMapper;
import com.qf.java2108.demo04.pojo.ReaderInfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author ghy
 * @version 1.0
 * @date 2022-03-11
 **/
@SpringBootTest
public class SpringBootDemo04ApplicationTest {

    @Autowired
    private ReaderInfoMapper readerInfoMapper;

    /**
     *
     **/
    @Test
    public void mybatisPlusQuickTest() throws Exception {
        List<ReaderInfo> list = readerInfoMapper.selectList(null);
        for (ReaderInfo readerInfo : list) {
            System.out.println(readerInfo);
        }

    }

}
测试效果

4、注解

4.1 @TableName

  • 映射数据库表,默认情况下,会把实体类名作为表名去映射

4.2 @TableId

  • 映射主键
  • type属性:指定主键生成策略
    • 插入时,如果主键是自增的,那么就无需指定主键的值

4.3 @TableField

  • value属性:指定数据库表的字段名

    • 当数据库表的字段名跟Java实体属性名不一致且也不满足驼峰命名时,必须使用@TableField来指定当前属性跟数据库表的哪个字段进行映射
  • select属性:查询时,是否查询该属性对应的字段值

    • 默认值是true,要查询
    • false:不查询该属性对应的字段值
  • exist:表示当前属性在数据库表中是否有对应的字段【一般在映射实体和集合时会指定】

    • 默认值是true,是有的
    • false:没有对应的字段
    //表示当前属性在数据库表中没有对应的字段
    @TableField(exist = false)
    private Admin admin;
    

5、常用API

增删改返回的都是影响行数

5.1 增加

/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
  • 注意

    • @TableId(type = IdType.AUTO)  //表示主键
      private Long id;
      
      • 指定@TableId注解的type属性为IdType.AUTO值,表示插入记录使用数据库主键自增特性
    • 会自动返回插入记录的主键值

5.2 删除

/**
 * 根据 ID 删除
 *
 * @param id 主键ID
 */
int deleteById(Serializable id);

5.3 修改

/**
 * 根据 ID 修改
 *
 * @param entity 实体对象
 */
int updateById(@Param(Constants.ENTITY) T entity);
动态更新
MybatisPlus概述及使用_第2张图片

5.4 查询

/**
 * select
 **/
@Test
public void selectTest() throws Exception {
    //ReaderInfo readerInfo = readerInfoMapper.selectById(1);
    //System.out.println("readerInfo = " + readerInfo);
//
    //List readerInfos = readerInfoMapper.selectBatchIds(Arrays.asList(1, 10, 2, 30));
    //for (ReaderInfo info : readerInfos) {
    //    System.out.println(info);
    //}

    //List readerInfos = readerInfoMapper.selectList(null);

    //根据条件查询
    //QueryWrapper wrapper = new QueryWrapper<>();
    //wrapper.eq("phone", "13512345678");
    //wrapper.gt("update_time", java.sql.Date.valueOf("2000-12-12"));
    //wrapper.likeRight("reader_name","l");
    参数一:是否需要进行排序
    //wrapper.orderBy(true, true, "id");
    //wrapper.orderByDesc("update_time");
    //List readerInfos = readerInfoMapper.selectList(wrapper);
    
    //Map map = new HashMap<>();
    //map.put("phone","13512345678");
    //List readerInfos = readerInfoMapper.selectByMap(map);

    //QueryWrapper wrapper = new QueryWrapper<>();
    //wrapper.eq("phone", "13512345678");
    //wrapper.gt("update_time", java.sql.Date.valueOf("2000-12-12"));
    //Integer count = readerInfoMapper.selectCount(wrapper);
    //System.out.println("count = " + count);

    //QueryWrapper wrapper = new QueryWrapper<>();
    //wrapper.eq("reader_name", "lisi");
    通过非主键查询单条记录
    //ReaderInfo readerInfo = readerInfoMapper.selectOne(wrapper);
    //System.out.println("readerInfo = " + readerInfo);

    QueryWrapper<ReaderInfo> wrapper = new QueryWrapper<>();
    wrapper.eq("reader_name", "lisi");
    List<Object> objects = readerInfoMapper.selectObjs(wrapper);
    for (Object object : objects) {
        System.out.println("object = " + object);
    }

    /*for (ReaderInfo info : readerInfos) {
        System.out.println(info);
    }*/

}

5.5 分页插件【了解】

  • 配置一个bean
package com.qf.java2108.demo04.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ghy
 * @version 1.0
 * @date 2022-03-11
 **/
@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        paginationInterceptor.setOverflow(true);
        // 设置最大单页限制数量,默认 50 条,-1 不受限制
        paginationInterceptor.setLimit(50);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize());
        return paginationInterceptor;
    }

}

  • selectPage(IPage, QueryWrapper)
@Test
public void mybatisPlusPaginationTest() throws Exception {
    IPage page = new Page<>();
    page.setCurrent(1);
    page.setSize(1);
    IPage ipage = readerInfoMapper.selectPage(page, null);
    System.out.println(ipage);
}

mybatis-plus的分页插件跟pagehepler没有冲突的,建议使用原生的

6.在Service层实现增强

  • 通过县相关配置,可以极大简化代码,实现在Service层的业务逻辑增强

  • Mapper层

    public interface StudentMapper extends BaseMapper<TbStudent> {
    
        List<TbStudent> findAll();
    }
    
  • Service接口层

    import com.baomidou.mybatisplus.extension.service.IService;
    public interface StudentService extends IService<TbStudent> {
    
    }
    
  • ServiceImpl层

    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    
    //实现类要继承 ServiceImpl<对应的mapper,实体类对象> 实现接口
    @Service
    public class StudentServiceImpl extends ServiceImpl<StudentMapper,TbStudent> implements StudentService{
    }
    
  • 测试

    	@Test
        public void findAll(){
            List list = studentService.list();
            System.out.println(list);
        }
    

7、自定义Mapper

  • 跟原生Mybatis开发接口没有任何区别,但是注意不要使用BaseMapper接口中的方法名
  • 可以在实体类中使用注解实现实体与数据库自定义映射(意味着不需要在xml映射文件中使用标签@ResultMap实现自定义映射了)
#日志打印
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #配置别名
  type-aliases-package: com.qf.pojo
  #扫描xml sql文件
  mapper-locations: classpath:mapper/*Mapper.xml

你可能感兴趣的:(java进阶,mybatis,mybatis-plus)