官网
MyBatis-Plus (baomidou.com)
创建并初始化数据库
见课件
快速创建工程
创建springboot工程
new project -> spring Initializr
mybatisplus依赖
1 2 3 4 5 6 7 8 9 10 11
| <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.3</version> </dependency>
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> </dependency>
|
配置application.properties
1 2 3 4 5 6
| spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456789
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
|
创建实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.example.mybatisplus_demo.entity;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
|
创建Mapepr接口
1 2 3 4 5 6 7 8 9
| package com.example.mybatisplus_demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mybatisplus_demo.entity.User;
@Repository public interface UserMapper extends BaseMapper<User> {
}
|
mapper扫描
注意这里有个易错点,mappersan内填写到Mapper文件存放的文件夹,而不是mapper文件
1 2 3 4 5 6 7 8 9
| @SpringBootApplication @MapperScan("com.example.mybatisplus_demo.mapper") public class MybatisplusDemoApplication {
public static void main(String[] args) { SpringApplication.run(MybatisplusDemoApplication.class, args); }
}
|
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.example.mybatisplus_demo;
import com.example.mybatisplus_demo.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest class MybatisplusDemoApplicationTests {
@Autowired private UserMapper userMapper;
@Test void contextLoads() { }
}
|
当前项目结构
基础CRUD接口
添加
不需要设置id主键的值,mybatisplus自动生成19位id
1 2 3 4 5
| @Test void addUser() { int insert = userMapper.insert(new User(null, "爱丽丝", 12, "Alice@qq.com")); System.out.println("insert: " + insert); }
|
主键生成策略
分布式系统唯一ID生成方案汇总 - nick hao - 博客园 (cnblogs.com)
- 自动增长
- UUID
- Redis生成
- snowflake雪花算法
mybatisplus中指定策略如下
1 2
| @TableId(type = IdType.AUTO) private Long id;
|
修改
1 2 3 4
| @Test void updateUser() { userMapper.updateById(new User(2L, "Jacks", 11, "Jacks@qq.com")); }
|
自动填充
为实体类添加带有注解的属性
1 2 3 4 5 6 7
| @TableField(fill = FieldFill.INSERT) private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime;
|
创建handler类,并实现接口MetaObjectHandler的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.example.mybatisplus_demo.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;
import java.util.Date;
@Component public class MyMetaObjectHandler implements MetaObjectHandler {
@Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); }
@Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("updateTime", new Date(), metaObject); } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Test void addUser() { User user = new User(); user.setName("岳不群1"); user.setAge(70); user.setEmail("lucy@qq.com");
int insert = userMapper.insert(user); System.out.println("insert:" + insert); }
@Test void updateUser() {
User user = new User(); user.setId(1439818355027558402L); user.setAge(120);
int row = userMapper.updateById(user); System.out.println(row); }
|
乐观锁
主要解决:丢失更新
为实体类添加带注解的属性
1 2 3
| @Version @TableField(fill = FieldFill.INSERT) private Integer version;
|
配置乐观锁插件,可以写在独立的配置类中(MapperScan也可以写在该配置类中)
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Configuration @MapperScan("com.example.mybatisplus_demo.mapper") public class MpConfig {
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; } }
|
编写handler类
1 2 3 4 5 6 7
| @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); this.setFieldValByName("version", 1, metaObject); }
|
测试
1 2 3 4 5 6 7 8
| @Test void testOptimisticLockerInnerInterceptor() { User user = userMapper.selectById(1439842460539846658L); user.setAge(44); userMapper.updateById(user); }
|
查询
批量查询
1 2 3 4 5
| @Test void testSelect() { List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L)); System.out.println(users); }
|
分页查询
在配置类中配置分页插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Configuration @MapperScan("com.example.mybatisplus_demo.mapper") public class MpConfig {
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
|
测试
1 2 3 4 5 6 7 8 9
| @Test void testPage() { Page<User> page = new Page<>(1, 2); Page<User> page1 = userMapper.selectPage(page, null); System.out.println(page1); }
|
删除
物理删除:真实删除,将数据从数据库中删除
逻辑删除:假删除,根据字段状态判断
批量删除(物理删除)
1 2 3 4
| @Test void testDelete() { userMapper.deleteBatchIds(Arrays.asList(1L, 2L)); }
|
逻辑删除
在实体类中添加带注释的属性(可以再加上TableField设置默认值等)
1 2
| @TableLogic private Integer deleted;
|
高版本已不需要在配置文件中添加插件
测试
1 2 3 4
| @Test void testDelete() { userMapper.deleteBatchIds(Arrays.asList(1L, 2L)); }
|
逻辑删除之后的数据在查询的时候不会被查询到(添加了额外的条件deleted=0)
条件构造器
1 2 3 4 5 6 7 8 9
| @Test void testWrapper() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.ge("age", 20).le("age", 40); List<User> users = userMapper.selectList(wrapper); System.out.println(users); }
|
代码生成器