本人是一名物联网工程专业的学生,写博客即是为了记录自己的学习历程,又希望能够帮助到很多和自己一样处于起步阶段的萌新。
临渊羡鱼,不如退而结网。一起加油!
博客主页:https://blog.csdn.net/qq_44895397
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
mybatis-plus-boot-starter、MySQL依赖:
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在 application.properties 配置文件中添加 MySQL 数据库的相关配置
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=yky
@Mapper
public interface StudentMapper extends BaseMapper<tStudent> {
}
注意数据库表名和实体类名称的关系:
控制台输出sql语句:
核心配置文件配置
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
@SpringBootTest
public class Mybatisplusdemo01ApplicationTests {
@Autowired
private StudentMapper studentMapper;
@Test
void contextLoads() {
List<tStudent> students = studentMapper.selectList(null);
for (tStudent s : students) {
System.out.println(s);
}
}
}
直接调用BaseMapper接口中的方法即可
//插入操作
@Test
public void add(){
tStudent student = new tStudent();
student.setName("爱敲代码的小游子");
student.setAge(19);
studentMapper.insert(student);
}
MyBatis-Plus默认的主键策略是:ID_WORKER
全局唯一ID
@TableId(type = IdType.AUTO)
@TableId(type = IdType.AUTO)
private Integer id;
#全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto
@Test
public void updateStudent() {
tStudent student = new tStudent();
student.setId(1009);
student.setName("东方不败");
studentMapper.updateById(student);
}
//自动填充
@TableField(fill = FieldFill.INSERT)
private Date create_time;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date update_time;
@Component
public class MyMateObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("update_time",new Date(),metaObject);
this.setFieldValByName("create_time",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("update_time",new Date(),metaObject);
}
}
TableField
注解,属性fill
选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段MyMetaObjectHandler
在 Spring Boot 中需要声明@Component
或@Bean
注入主要解决:丢失更新,也就是说实现线程安全的数据更新
/**
* 乐观锁插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
//乐观锁
@TableField(fill = FieldFill.INSERT)
@Version
private Integer version;
@Test
void selecttStudentById() {
tStudent students = studentMapper.selectById(1004);
System.out.println(students);
}
@Test
void selecttStudentById() {
List<tStudent> tStudents = studentMapper.selectBatchIds(Arrays.asList(1001, 1002, 1003));
System.out.println(tStudents );
}
通过map封装查询条件
@Test
public void testSelectByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name", "爱敲代码的小游子");
map.put("age", 19);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
//创建page对象
//两个参数:当前页和每页显示记录数
Page<tStudent> studentPage = new Page<>(1,3);
@Test
public void pageHander(){
//创建page对象
//两个参数:当前页和每页显示记录数
Page<tStudent> studentPage = new Page<>(1,3);
//调用分页查询方法
//分页查询过程中,把分页所有的数据封装到page对象里面
studentMapper.selectPage(studentPage,null);
studentPage.getCurrent();//当前页
studentPage.getRecords();//每页数据的list集合
studentPage.getSize();//每页显示记录数
studentPage.getTotal();//总记录数
studentPage.getPages();//总页数
System.out.println(studentPage.getPages());
studentPage.hasNext();//判断是否还有下一页
studentPage.hasPrevious();//判断是否还有上一页
}
@Test
public void testDeleteById(){
int result = userMapper.deleteById(8L);
System.out.println(result);
}
@Test
public void testDeleteBatchIds() {
int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
System.out.println(result);
}
@Test
public void testDeleteByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Helen");
map.put("age", 18);
int result = userMapper.deleteByMap(map);
System.out.println(result);
}
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
在数据库中增加deleted字段时设置默认值后不需要再在这里设置默认值
this.setFieldValByName("deleted",0,metaObject);
##逻辑删除配置
#mybatis-plus.global-config.db-config.logic-delete-value=1
#mybatis-plus.global-config.db-config.logic-not-delete-value=0
了解更多可以参考官方文档:https://mp.baomidou.com/
QueryWrapper<tStudent> wrapper = new QueryWrapper<>();
public void text(){
QueryWrapper<tStudent> wrapper = new QueryWrapper<>();
wrapper.ge("id",1004);
wrapper.le("age",50);
List<tStudent> tStudents = studentMapper.selectList(wrapper);
System.out.println(tStudents);
}
eq("name", "老王")--->name = '老王'
包含大小边界
between("age", 18, 30)--->age between 18 and 30
allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
allEq({id:1,name:"老王",age:null})
—>id = 1 and name = '老王' and age is null
allEq({id:1,name:"老王",age:null}, false)
—> id = 1 and name = '老王'
无视优化规则直接拼接到 sql 的最后
注意事项:
//复杂条件查询
@Test
public void select(){
QueryWrapper<tStudent> wrapper = new QueryWrapper<>();
wrapper.last("and name = ''");
List<tStudent> tStudents = studentMapper.selectList(wrapper);
System.out.println(tStudents);
}