Geeks_Z の Blog Geeks_Z の Blog
首页
  • 学习笔记

    • 《HTML》
    • 《CSS》
    • 《JavaWeb》
    • 《Vue》
  • 后端文章

    • Linux
    • Maven
    • 汇编语言
    • 软件工程
    • 计算机网络概述
    • Conda
    • Pip
    • Shell
    • SSH
    • Mac快捷键
    • Zotero
  • 学习笔记

    • 《数据结构与算法》
    • 《算法设计与分析》
    • 《Spring》
    • 《SpringMVC》
    • 《SpringBoot》
    • 《SpringCloud》
    • 《Nginx》
  • 深度学习文章
  • 学习笔记

    • 《PyTorch》
    • 《ReinforementLearning》
    • 《MetaLearning》
  • 学习笔记

    • 《高等数学》
    • 《线性代数》
    • 《概率论与数理统计》
  • 增量学习
  • 哈希学习
GitHub (opens new window)

Geeks_Z

AI小学生
首页
  • 学习笔记

    • 《HTML》
    • 《CSS》
    • 《JavaWeb》
    • 《Vue》
  • 后端文章

    • Linux
    • Maven
    • 汇编语言
    • 软件工程
    • 计算机网络概述
    • Conda
    • Pip
    • Shell
    • SSH
    • Mac快捷键
    • Zotero
  • 学习笔记

    • 《数据结构与算法》
    • 《算法设计与分析》
    • 《Spring》
    • 《SpringMVC》
    • 《SpringBoot》
    • 《SpringCloud》
    • 《Nginx》
  • 深度学习文章
  • 学习笔记

    • 《PyTorch》
    • 《ReinforementLearning》
    • 《MetaLearning》
  • 学习笔记

    • 《高等数学》
    • 《线性代数》
    • 《概率论与数理统计》
  • 增量学习
  • 哈希学习
GitHub (opens new window)
  • Linux

  • 数据结构与算法

  • 算法设计与分析

  • Java

  • Python

  • 设计模式

  • 计算机网络

  • Spring笔记

  • SpringMVC笔记

  • SpringBoot笔记

  • SpringSecurity

  • Elasticsearch笔记

  • RabbitMQ笔记

  • Docker笔记

  • MySQL

  • Redis

  • Mybatis

  • MybatisPlus

    • Mybatis-Plus介绍
    • 快速开始
    • Mybatis + MP
    • Spring + Mybatis + MP
    • SpringBoot + Mybatis + MP
    • BaseMapper
    • 通用 CRUD
      • 通用 CRUD
        • 插入操作
        • 方法定义
        • 测试用例
        • 控制台输出
        • @TableId
        • 修改User类
        • @TableField
        • 更新操作
        • 根据id更新
        • 方法定义
        • 测试
        • 控制台输出
        • 根据条件更新
        • 方法定义
        • 测试用例
        • 删除操作
        • deleteById
        • 方法定义
        • 测试用例
        • 控制台打印
        • deleteByMap
        • 方法定义
        • 测试用例
        • 控制台打印
        • delete
        • 方法定义
        • 测试用例
        • 控制台打印
        • deleteBatchIds
        • 方法定义
        • 测试用例
        • 控制台打印
        • 查询操作
        • selectById
        • 方法定义
        • 测试用例
        • 控制台打印
        • selectBatchId
        • 方法定义
        • 测试用例
        • 控制台打印
        • selectOne
        • 方法定义
        • 测试用例
        • 控制台打印
        • selectCount
        • 方法定义
        • 测试用例
        • 控制台打印
        • selectList
        • 方法定义
        • 测试用例
        • 控制台打印
        • selectPage
        • 方法定义
        • 配置分页插件
        • 测试用例
        • 控制台打印
        • 配置
        • 基本配置
        • configLocation
        • mapperLocations
        • typeAliasesPackage
        • 进阶配置
        • mapUnderscoreToCamelCase
        • cacheEnabled
        • DB 策略配置
        • idType
        • tablePrefix
    • Service CRUD 接口
  • Nginx

  • Kubernetes笔记

  • Git

  • Software

  • 微服务笔记

  • bug

  • BackEndNotes
  • MybatisPlus
Geeks_Z
2023-02-20
目录

通用 CRUD

通用 CRUD

通过前面的学习,我们了解到通过继承BaseMapper就可以获取到各种各样的单表操作,接下来我们将详细讲解这些 操作。

插入操作

方法定义

/**
 * 插入一条记录
 *
 * @param entity 实体对象
 */
int insert(T entity);
1
2
3
4
5
6

测试用例

package org.hong;

import org.hong.mapper.UserMapper;
import org.hong.pojo.User;
import org.junit.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.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestUserMapper {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testInsert(){
        User user = new User();
        user.setEmail("baomidou@qq.com");
        user.setAge(8);
        user.setUserName("mybatis-plus");
        user.setName("baomidou");
        user.setPassword("123456");

        // 返回数据库受影响的行数
        int result = this.userMapper.insert(user);
        System.out.println("result => " + result);

        // 获取自增后的id值, 自增后的id值会回填到user对象中
        System.out.println("id => " + user.getId());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

控制台输出

[main] [org.hong.mapper.UserMapper.insert]-[DEBUG] ==>  Preparing: INSERT INTO tb_user ( id, user_name, password, name, age, email ) VALUES ( ?, ?, ?, ?, ?, ? ) 
[main] [org.hong.mapper.UserMapper.insert]-[DEBUG] ==> Parameters: 1370007317083680769(Long), mybatis-plus(String), 123456(String), baomidou(String), 8(Integer), baomidou@qq.com(String)
[main] [org.hong.mapper.UserMapper.insert]-[DEBUG] <==    Updates: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@43a51d00]
result => 1
id => 1370007317083680769
1
2
3
4
5
6

可以看到,数据已经写入到了数据库,但是,id的值不正确,我们期望的是数据库自增长,实际是MP生成了id的值写入到了数据库

@TableId

如何设置id的生成策略呢? MP支持的id策略:

package com.baomidou.mybatisplus.annotation;

import lombok.Getter;

/**
 * 生成ID类型枚举类
 *
 * @author hubin
 * @since 2015-11-10
 */
@Getter
public enum IdType {
    /**
     * 数据库ID自增
     */
    AUTO(0),
    /**
     * 该类型为未设置主键类型
     */
    NONE(1),
    /**
     * 用户输入ID
     * <p>该类型可以通过自己注册自动填充插件进行填充</p>
     */
    INPUT(2),

    /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
    /**
     * 全局唯一ID (idWorker)
     */
    ID_WORKER(3),
    /**
     * 全局唯一ID (UUID)
     */
    UUID(4),
    /**
     * 字符串全局唯一ID (idWorker 的字符串表示)
     */
    ID_WORKER_STR(5);

    private final int key;

    IdType(int key) {
        this.key = key;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

修改User类

package org.hong.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;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

再次运行,数据插入成功。

@TableField

在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有2个:

1、对象中的属性名和字段名不一致的问题(非驼峰)

2、对象中的属性字段在表中不存在的问题

package org.hong.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
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;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String userName;
    
    @TableField(select = false) // select: 设置是否在查询带上该字段; 如果为false, 则在查询时就不会带上该字段, 更不会封装这个字段
    private String password;
    
    private String name;
    private Integer age;
    
    @TableField(value = "email") // value: 指定数据库表中的字段名; 查询时会使用 (email as mail) 的方式
    private String mail;

    @TableField(exist = false) // exist: 设置属性是否在数据库中存在
    private String address; // 这个属性在数据库表中是不存在的
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

更新操作

在MP中,更新操作有2种,一种是根据id更新,另一种是根据条件更新。

根据id更新

方法定义
/**
 * 根据 ID 修改
 *
 * @param entity 实体对象
 */
int updateById(@Param(Constants.ENTITY) T entity);
1
2
3
4
5
6
测试
package org.hong;

import org.hong.mapper.UserMapper;
import org.hong.pojo.User;
import org.junit.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.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestUserMapper {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(1L);
        user.setAge(18);
        int result = userMapper.updateById(user);
        System.out.println("result => " + result);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
控制台输出
[main] [org.hong.mapper.UserMapper.updateById]-[DEBUG] ==>  Preparing: UPDATE tb_user SET age=? WHERE id=? 
[main] [org.hong.mapper.UserMapper.updateById]-[DEBUG] ==> Parameters: 18(Integer), 1(Long)
[main] [org.hong.mapper.UserMapper.updateById]-[DEBUG] <==    Updates: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@363a3d15]
result => 1
1
2
3
4
5

根据条件更新

方法定义
/**
 * 根据 whereEntity 条件,更新记录
 *
 * @param entity        实体对象 (set 条件值, 默认为null的字段不会加入到set中)
 * @param updateWrapper 实体对象封装操作类(可以为 null, 用于生成 where 语句)
 */
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
1
2
3
4
5
6
7
测试用例
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestUserMapper {
	@Test
    public void testUpdate(){
        User user = new User();
        user.setAge(25);// 更新的字段
        user.setPassword("666888");

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // 更新条件: 匹配 user_name = zhangsan 的用户
        wrapper.eq("user_name", "zhangsan");

        // 根据条件跟新
        int result = userMapper.update(user, wrapper);
        System.out.println("result => " + result);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

测试结果

[main] [org.hong.mapper.UserMapper.update]-[DEBUG] ==>  Preparing: UPDATE tb_user SET password=?, age=? WHERE user_name = ? 
[main] [org.hong.mapper.UserMapper.update]-[DEBUG] ==> Parameters: 666888(String), 25(Integer), zhangsan(String)
[main] [org.hong.mapper.UserMapper.update]-[DEBUG] <==    Updates: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4fad6218]
result => 1
1
2
3
4
5

或者,通过UpdateWrapper进行更新

@Test
public void testUpdate2(){
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.set("age", 21).set("password", "999999") // 更新的字段
    .eq("user_name", "zhangsan"); // 更新条件

    // 根据条件跟新
    int result = userMapper.update(null, wrapper);
    System.out.println("result => " + result);
}
1
2
3
4
5
6
7
8
9
10

测试结果

[main] [org.hong.mapper.UserMapper.update]-[DEBUG] ==>  Preparing: UPDATE tb_user SET age=?,password=? WHERE user_name = ? 
[main] [org.hong.mapper.UserMapper.update]-[DEBUG] ==> Parameters: 21(Integer), 999999(String), zhangsan(String)
[main] [org.hong.mapper.UserMapper.update]-[DEBUG] <==    Updates: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6ea04618]
result => 1
1
2
3
4
5

均可达到更新的效果。 关于wrapper更多的用法后面会详细讲解。

删除操作

deleteById

方法定义
/**
 * 根据 ID 删除
 *
 * @param id 主键ID
 */
int deleteById(Serializable id);
1
2
3
4
5
6
测试用例
@Test
public void testDeleteById(){
    // 根据id删除数据
    int result = userMapper.deleteById(9);
    System.out.println("result => " + result);
}
1
2
3
4
5
6
控制台打印
[main] [org.hong.mapper.UserMapper.deleteById]-[DEBUG] ==>  Preparing: DELETE FROM tb_user WHERE id=? 
[main] [org.hong.mapper.UserMapper.deleteById]-[DEBUG] ==> Parameters: 9(Integer)
[main] [org.hong.mapper.UserMapper.deleteById]-[DEBUG] <==    Updates: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1640c151]
result => 1
1
2
3
4
5

deleteByMap

方法定义
/**
 * 根据 columnMap 条件,删除记录,条件之间是and的关系
 *
 * @param columnMap 表字段 map 对象
 */
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
1
2
3
4
5
6
测试用例
@Test
public void testDeleteMap(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("user_name", "zhangsan");
    map.put("password", "123456");

    // 根据map删除数据, 多条件之间是and的关系
    int result = userMapper.deleteByMap(map);
    System.out.println("result => " + result);
}
1
2
3
4
5
6
7
8
9
10
控制台打印
[main] [org.hong.mapper.UserMapper.deleteByMap]-[DEBUG] ==>  Preparing: DELETE FROM tb_user WHERE password = ? AND user_name = ? 
[main] [org.hong.mapper.UserMapper.deleteByMap]-[DEBUG] ==> Parameters: 123456(String), zhangsan(String)
[main] [org.hong.mapper.UserMapper.deleteByMap]-[DEBUG] <==    Updates: 0
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5c20aab9]
result => 0
1
2
3
4
5

delete

方法定义
/**
 * 根据 entity 条件,删除记录
 *
 * @param wrapper 实体对象封装操作类(可以为 null)
 */
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
1
2
3
4
5
6
测试用例
@Test
    public void testDelete(){
        // 用法一:
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_name", "mybatis-plus")
//                .eq("password", "123456");

        // 用法二:
        User user = new User();
        user.setUserName("mybatis-plus");
        user.setPassword("123456");
        // 将实体对象进行包装, 包装为操作条件
        QueryWrapper<User> wrapper = new QueryWrapper<User>(user);

        // 根据包装条件做删除
        int result = userMapper.delete(wrapper);
        System.out.println("result => " + result);
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
控制台打印
[main] [org.hong.mapper.UserMapper.delete]-[DEBUG] ==>  Preparing: DELETE FROM tb_user WHERE user_name = ? AND password = ? 
[main] [org.hong.mapper.UserMapper.delete]-[DEBUG] ==> Parameters: mybatis-plus(String), 123456(String)
[main] [org.hong.mapper.UserMapper.delete]-[DEBUG] <==    Updates: 2
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6dd82486]
result => 2
1
2
3
4
5

deleteBatchIds

方法定义
/**
 * 删除(根据ID 批量删除)
 *
 * @param idList 主键ID列表(不能为 null 以及 empty)
 */
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
1
2
3
4
5
6
测试用例
@Test
public void testDelteBatchIds(){
    // 根据id批量删除数据
    int result = userMapper.deleteBatchIds(Arrays.asList(10, 11, 12));
    System.out.println("result => " + result);
}
1
2
3
4
5
6
控制台打印
[main] [org.hong.mapper.UserMapper.deleteBatchIds]-[DEBUG] ==>  Preparing: DELETE FROM tb_user WHERE id IN ( ? , ? , ? ) 
[main] [org.hong.mapper.UserMapper.deleteBatchIds]-[DEBUG] ==> Parameters: 10(Integer), 11(Integer), 12(Integer)
[main] [org.hong.mapper.UserMapper.deleteBatchIds]-[DEBUG] <==    Updates: 3
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@74aa9c72]
result => 3
1
2
3
4
5

查询操作

MP提供了多种查询操作,包括根据id查询、批量查询、查询单条数据、查询列表、分页查询等操作。

selectById

方法定义
/**
 * 根据 ID 查询
 *
 * @param id 主键ID
 */
T selectById(Serializable id);
1
2
3
4
5
6
测试用例
@Test
public void testSelectById(){
    User user = userMapper.selectById(1L);
    System.out.println(user);
}
1
2
3
4
5
控制台打印
[main] [org.hong.mapper.UserMapper.selectById]-[DEBUG] ==>  Preparing: SELECT id,user_name,name,age,email FROM tb_user WHERE id=? 
[main] [org.hong.mapper.UserMapper.selectById]-[DEBUG] ==> Parameters: 1(Long)
[main] [org.hong.mapper.UserMapper.selectById]-[DEBUG] <==      Total: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@e48bf9a]
User(id=1, userName=zhangsan, password=null, name=张三, age=21, email=test1@itcast.cn, address=null)
1
2
3
4
5

selectBatchId

方法定义
/**
 * 查询(根据ID 批量查询)
 *
 * @param idList 主键ID列表(不能为 null 以及 empty)
 */
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
1
2
3
4
5
6
测试用例
@Test
public void testSelectBatchIds(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L));
    for (User user : users) {
        System.out.println(user);
    }
}
1
2
3
4
5
6
7
控制台打印
[main] [org.hong.mapper.UserMapper.selectBatchIds]-[DEBUG] ==>  Preparing: SELECT id,user_name,name,age,email FROM tb_user WHERE id IN ( ? , ? , ? ) 
[main] [org.hong.mapper.UserMapper.selectBatchIds]-[DEBUG] ==> Parameters: 1(Long), 2(Long), 3(Long)
[main] [org.hong.mapper.UserMapper.selectBatchIds]-[DEBUG] <==      Total: 3
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@c1fca2a]
User(id=1, userName=zhangsan, password=null, name=张三, age=21, email=test1@itcast.cn, address=null)
User(id=2, userName=lisi, password=null, name=李四, age=20, email=test2@itcast.cn, address=null)
User(id=3, userName=wangwu, password=null, name=王五, age=28, email=test3@itcast.cn, address=null)
1
2
3
4
5
6
7

selectOne

方法定义
/**
 * 根据 entity 条件,查询一条记录
 *
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
1
2
3
4
5
6
测试用例
@Test
public void testSelectOne(){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("id", "3");
    // 查询的数据如果大于1则会保存, 因此查询结果要么为null要么为1
    User user = userMapper.selectOne(wrapper);
    System.out.println(user);
}
1
2
3
4
5
6
7
8
控制台打印
[main] [org.hong.mapper.UserMapper.selectOne]-[DEBUG] ==>  Preparing: SELECT id,user_name,name,age,email FROM tb_user WHERE id = ? 
[main] [org.hong.mapper.UserMapper.selectOne]-[DEBUG] ==> Parameters: 3(String)
[main] [org.hong.mapper.UserMapper.selectOne]-[DEBUG] <==      Total: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1aac188d]
User(id=3, userName=wangwu, password=null, name=王五, age=28, email=test3@itcast.cn, address=null)
1
2
3
4
5

selectCount

方法定义
/**
 * 根据 Wrapper 条件,查询总记录数
 *
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
1
2
3
4
5
6
测试用例
@Test
public void testSelectCount(){
    // 如果wrapper为null, 则没有查询条件, 就是查询所有
    Integer count = userMapper.selectCount(null);
    System.out.println("count => " + count);
}
1
2
3
4
5
6
控制台打印
[main] [org.hong.mapper.UserMapper.selectCount]-[DEBUG] ==>  Preparing: SELECT COUNT( 1 ) FROM tb_user 
[main] [org.hong.mapper.UserMapper.selectCount]-[DEBUG] ==> Parameters: 
[main] [org.hong.mapper.UserMapper.selectCount]-[DEBUG] <==      Total: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@164a62bf]
count => 5
1
2
3
4
5

selectList

方法定义
/**
 * 根据 entity 条件,查询全部记录
 *
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
1
2
3
4
5
6
测试用例
@Test
public void testSelectList(){
    QueryWrapper<User> wrapper = new QueryWrapper<User>();
    // 设置查询条件
    wrapper.like("email", "itcast");
    List<User> users = userMapper.selectList(wrapper);
    for (User user : users) {
        System.out.println(user);
    }
}
1
2
3
4
5
6
7
8
9
10
控制台打印
[main] [org.hong.mapper.UserMapper.selectList]-[DEBUG] ==>  Preparing: SELECT id,user_name,name,age,email FROM tb_user WHERE email LIKE ? 
[main] [org.hong.mapper.UserMapper.selectList]-[DEBUG] ==> Parameters: %itcast%(String)
[main] [org.hong.mapper.UserMapper.selectList]-[DEBUG] <==      Total: 5
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4fad6218]
User(id=1, userName=zhangsan, password=null, name=张三, age=21, email=test1@itcast.cn, address=null)
User(id=2, userName=lisi, password=null, name=李四, age=20, email=test2@itcast.cn, address=null)
User(id=3, userName=wangwu, password=null, name=王五, age=28, email=test3@itcast.cn, address=null)
User(id=4, userName=zhaoliu, password=null, name=赵六, age=21, email=test4@itcast.cn, address=null)
User(id=5, userName=sunqi, password=null, name=孙七, age=24, email=test5@itcast.cn, address=null)
1
2
3
4
5
6
7
8
9

selectPage

方法定义
/**
 * 根据 entity 条件,查询全部记录(并翻页)
 *
 * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
1
2
3
4
5
6
7
配置分页插件
package org.hong.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@MapperScan({"org.hong.mapper"})
@Configuration
public class MyBatisPlusConfig {
    // 配置分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
测试用例
@Test
public void testSelectPage(){
    QueryWrapper<User> wrapper = new QueryWrapper<User>();
    // 设置查询条件
    wrapper.like("email", "itcast");

    Page<User> page = new Page<User>();
    // 设置当前页数
    page.setCurrent(1);
    // 设置每页的数量
    page.setSize(1);

    IPage<User> userIPage = userMapper.selectPage(page, wrapper);
    System.out.println("数据总条数:" + userIPage.getTotal());
    System.out.println("数据总页数:" + userIPage.getPages());
    System.out.println("当前页数:" + userIPage.getCurrent());
    // 获取查询数据
    List<User> users = userIPage.getRecords();
    for (User user : users) {
        System.out.println(user);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
控制台打印
[main] [com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize]-[DEBUG] JsqlParserCountOptimize sql=SELECT  id,user_name,name,age,email  FROM tb_user 
 
 WHERE email LIKE ?
[main] [org.hong.mapper.UserMapper.selectPage]-[DEBUG] ==>  Preparing: SELECT COUNT(1) FROM tb_user WHERE email LIKE ? 
[main] [org.hong.mapper.UserMapper.selectPage]-[DEBUG] ==> Parameters: %itcast%(String)
[main] [org.hong.mapper.UserMapper.selectPage]-[DEBUG] ==>  Preparing: SELECT id,user_name,name,age,email FROM tb_user WHERE email LIKE ? LIMIT ?,? 
[main] [org.hong.mapper.UserMapper.selectPage]-[DEBUG] ==> Parameters: %itcast%(String), 0(Long), 1(Long)
[main] [org.hong.mapper.UserMapper.selectPage]-[DEBUG] <==      Total: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7c9bdee9]
数据总条数:5
数据总页数:5
当前页数:1
User(id=1, userName=zhangsan, password=null, name=张三, age=21, email=test1@itcast.cn, address=null)
1
2
3
4
5
6
7
8
9
10
11
12
13

配置

在MP中有大量的配置,其中有一部分是Mybatis原生的配置,另一部分是MP的配置,详情:https://mybatis.plus/config/ 。

基本配置

configLocation

MyBatis 配置文件位置,如果您有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。 MyBatis Configuration 的具体内容请参考MyBatis 官方文档

Spring Boot:

mybatis-plus:
  config-location: classpath:mybatis-config.xml
1
2

Spring MVC

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
1
2
3

mapperLocations

MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。

Spring Boot:

mybatis-plus:    
  mapper-locations: classpath*:mapper/**/*.xml ## 默认就是这个值
1
2

Spring MVC:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="mapperLocations" value="classpath*:mapper/**/*.xml"/>
</bean>
1
2
3

Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件)

typeAliasesPackage

MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使 用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。

Spring Boot:

mybatis-plus:
  type-aliases-package: org.hong.pojo
1
2

Spring MVC:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
	<property name="typeAliasesPackage" value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
</bean>
1
2
3

进阶配置

本部分(Configuration)的配置大都为 MyBatis 原生支持的配置,这意味着您可以通过 MyBatis XML 配置文件的形 式进行配置。

mapUnderscoreToCamelCase

  • 类型: boolean
  • 默认值: true

是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属 性名 aColumn(驼峰命名) 的类似映射。

注意: 此属性在 MyBatis 中原默认值为 false,在 MyBatis-Plus 中,此属性也将用于生成最终的 SQL 的 select body 如果您的数据库命名符合规则无需使用 @TableField 注解指定数据库字段名

示例(SpringBoot):

#关闭自动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: false
1
2
3
4

cacheEnabled

  • 类型: boolean
  • 默认值: true

全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。

示例(SpringBoot):

mybatis-plus:
  configuration:
    cache-enabled: false
1
2
3

DB 策略配置

idType

  • 类型: com.baomidou.mybatisplus.annotation.IdType
  • 默认值: ID_WORKER

全局默认主键类型,设置后,即可省略实体对象中的 @TableId(type = IdType.AUTO) 配置。

SpringBoot:

mybatis-plus:
  global-config:
    db-config:
      id-type: auto
1
2
3
4

SpringMVC:

<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="globalConfig" ref="globalConfig"/>
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
    <property name="dbConfig" ref="dbConfig"/>
</bean>
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
    <property name="idType" value="AUTO"/>
</bean>
1
2
3
4
5
6
7
8
9
10
11

tablePrefix

  • 类型: String
  • 默认值: null

表名前缀,全局配置后可省略符合前缀规范的@TableName()配置。

SpringBoot:

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tb_
1
2
3
4

SpringMVC:

<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="globalConfig" ref="globalConfig"/>
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
    <property name="dbConfig" ref="dbConfig"/>
</bean>
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
    <property name="idType" value="AUTO"/>
    <property name="tablePrefix" value="tb_"/>
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
上次更新: 2024/03/29, 08:56:31
BaseMapper
Service CRUD 接口

← BaseMapper Service CRUD 接口→

最近更新
01
并行训练
03-29
02
tensor维度转换
03-26
03
ResNet源码解读
03-23
更多文章>
Theme by Vdoing | Copyright © 2022-2024 Geeks_Z | MIT License
京公网安备 11010802040735号 | 京ICP备2022029989号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式