mybatis-plus简介
快速入门
创建数据库
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 | #创建用户表 CREATE TABLE user ( id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键', name VARCHAR(30) DEFAULT NULL COMMENT '姓名', age INT(11) DEFAULT NULL COMMENT '年龄', email VARCHAR(50) DEFAULT NULL COMMENT '邮箱', manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id', create_time DATETIME DEFAULT NULL COMMENT '创建时间', CONSTRAINT manager_fk FOREIGN KEY (manager_id) REFERENCES user (id) ) ENGINE=INNODB CHARSET=UTF8; #初始化数据: INSERT INTO user (id, name, age, email, manager_id , create_time) VALUES (1087982257332887553, '大boss', 40, '[email protected]', NULL , '2019-01-11 14:20:20'), (1088248166370832385, '王天风', 25, '[email protected]', 1087982257332887553 , '2019-02-05 11:12:22'), (1088250446457389058, '李艺伟', 28, '[email protected]', 1088248166370832385 , '2019-02-14 08:31:16'), (1094590409767661570, '张雨琪', 31, '[email protected]', 1088248166370832385 , '2019-01-14 09:15:15'), (1094592041087729666, '刘红雨', 32, '[email protected]', 1088248166370832385 , '2019-01-14 09:48:16'); |
pom.xml
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | <?xml version="1.0" encoding="UTF-8"?> <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.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.chaolong</groupId> <artifactId>first</artifactId> <version>0.0.1-SNAPSHOT</version> <name>first</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <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> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--引入mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> |
domian下的User.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package com.chaolong.first.domian; import lombok.Data; import java.util.Date; /** * @author: Chaolong * @create: 2020/06/07 **/ @Data public class User { private Long id; private String name; private Integer age; private String email; // 上级ID private Long managerId; private Date createTime; } |
dao下的UserMapper.class
1 2 3 4 5 6 7 8 9 10 11 12 | package com.chaolong.first.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.chaolong.first.domian.User; /** * @author: Chaolong * @create: 2020/06/07 **/ public interface UserMapper extends BaseMapper<User> { } |
配置文件 application.yml
1 2 3 4 5 6 | spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC username: root password: 123456 |
启动类 (application.class)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package com.chaolong.first; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.chaolong.first.dao") // 指定扫描Mapper接口的包路径 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } |
测试 ApplicationTests.class
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 | package com.chaolong.first; import com.chaolong.first.dao.UserMapper; import com.chaolong.first.domian.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class ApplicationTests { @Autowired private UserMapper userMapper; @Test void select() { List<User> users = userMapper.selectList(null); //users.forEach(System.out::println); users.forEach((user)->{ System.out.println(user); }); } } |
插入操作
application.yml 添加开启sql语句显示
1 2 3 | mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启sql 语句日志显示 |
insertTest.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @SpringBootTest class InsertTest { @Autowired private UserMapper userMapper; @Test void insert() { User user = new User(); user.setName("向dong"); user.setAge(40); user.setManagerId(1088248166370832385L); user.setCreateTime(new Date()); userMapper.insert(user); } } |
@TableName @TableId @TableField
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Data @TableName("user_2") // 与数据库中的哪一张表进行映射 public class User { @TableId("id") private Long id; @TableField("name") // 与表中的字段进行映射 private String name; private Integer age; private String email; // 上级ID private Long managerId; private Date createTime; } |
排除非表字段
1 2 | @TableField(exist =false) private int flag; |
查询操作
普通查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 /**
* 根据 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);
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 | @SpringBootTest class SelectTest { @Autowired private UserMapper userMapper; @Test void selectById() { User user = userMapper.selectById(1269485636327424002L); System.out.println(user); // SELECT id,name,age,email,manager_id,create_time FROM user WHERE id=? } @Test void selectByIds() { List<Long> idList = Arrays.asList(1094590409767661570L, 1088248166370832385L, 1269485636327424002L); List<User> users = userMapper.selectBatchIds(idList); users.forEach(System.out::println); // SELECT id,name,age,email,manager_id,create_time FROM user WHERE id IN ( ? , ? , ? ) } @Test void selectByMap() { Map<String,Object> map = new HashMap<>(); map.put("name","向南"); // key 为数据库中的字段 map.put("age","20"); List<User> users = userMapper.selectByMap(map); users.forEach(System.out::println); // SELECT id,name,age,email,manager_id,create_time FROM user WHERE name = ? AND age = ? } } |
以条件构造器为参数的查询
1
2
3
4
5
6 /**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | /** * 1、名字中包含雨并且年龄小于40 * name like '%雨%' and age<40 */ @Test void select1() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name", "雨").lt("age", 40); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (name LIKE ? AND age < ?) //==> Parameters: %雨%(String), 40(Integer) } /** * 2、名字中包含雨年并且龄大于等于20且小于等于40并且email不为空 * name like '%雨%' and age between 20 and 40 and email is not null */ @Test void select2() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name", "雨").between("age", 20, 40).isNotNull("email"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL) //==> Parameters: %雨%(String), 20(Integer), 40(Integer) } /** * 3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列 * name like '王%' or age>=25 order by age desc,id asc */ @Test void select3() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.likeRight("name", "王").or().gt("age", 25).orderByDesc("age").orderByAsc("id"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); // ==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (name LIKE ? OR age > ?) ORDER BY age DESC,id ASC //==> Parameters: 王%(String), 25(Integer) } /** * 4、创建日期为2019年2月14日并且直属上级为名字为王姓 * date_format(create_time,'%Y-%m-%d')='2019-02-14' and manager_id in (select id from user where name like '王%') */ @Test void select4() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.apply("date_format(create_time,'%Y-%m-%d')={0}", "2019-02-14").inSql("manager_id", "select id from user where name like '王%'"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (date_format(create_time,'%Y-%m-%d')=? AND manager_id IN (select id from user where name like '王%')) //==> Parameters: 2019-02-14(String) } /** * 5、名字为王姓并且(年龄小于40或邮箱不为空) * name like '王%' and (age<40 or email is not null) */ @Test void select5() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.likeRight("name", "王").and((qw) -> { qw.lt("age", 40).or().isNotNull("email"); }); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (name LIKE ? AND (age < ? OR email IS NOT NULL)) //==> Parameters: 王%(String), 40(Integer) } /** * 6、名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空) * name like '王%' or (age<40 and age>20 and email is not null) */ @Test void select6() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.likeRight("name", "王").or((qw) -> { qw.between("age", 20, 40).isNotNull("email"); }); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (name LIKE ? OR (age BETWEEN ? AND ? AND email IS NOT NULL)) //==> Parameters: 王%(String), 20(Integer), 40(Integer) } /** * 7、(年龄小于40或邮箱不为空)并且名字为王姓 * (age<40 or email is not null) and name like '王%' */ @Test void select7() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.nested((qw) -> { qw.lt("age", 40).or().isNotNull("email"); }).likeRight("name", "王"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE ((age < ? OR email IS NOT NULL) AND name LIKE ?) //==> Parameters: 40(Integer), 王%(String) } /** * 8、年龄为30、31、34、35 * age in (30、31、34、35) */ @Test void select8() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.in("age", Arrays.asList(31, 30, 34, 35)); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE (age IN (?,?,?,?)) //==> Parameters: 31(Integer), 30(Integer), 34(Integer), 35(Integer) } /** * 9、只返回满足条件的其中一条语句即可 * limit 1 */ @Test void select9() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.last("limit 1"); // 有sql注入风险 List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user limit 1 } |
select中字段不全出现的处理方法
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 | /** * 10、名字中包含雨并且年龄小于40(需求1加强版) * 第一种情况:select id,name * from user * where name like '%雨%' and age<40 */ @Test void select1Supper() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("name", "雨").lt("age", 40).select("id", "name"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name FROM user WHERE (name LIKE ? AND age < ?) //==> Parameters: %雨%(String), 40(Integer) } /** * 第二种情况:select id,name,age,email * from user * where name like '%雨%' and age<40 */ @Test void select2Supper() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.select(User.class, (info) -> { return !info.getColumn().equals("create_time")&&!info.getColumn().equals("manager_id"); }).like("name", "雨").lt("age", 40); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); //==> Preparing: SELECT id,name,age,email FROM user WHERE (name LIKE ? AND age < ?) //==> Parameters: %雨%(String), 40(Integer) } |