【引言】
在前面的博客中,有总结两篇与Mybatis-Plus相关的文章,《知道Mybatis,知道Mybatis-Plus么?》以及《自动生成代码配置》。Mybatis的增强版、更简洁的xml、更强大的代码生成,这些都很大程度上节省了我们的开发时间。
因为最近接触的项目中,用到了Mybatis-Plus,简单的增删改都不需要我们再去写方法,而对于查询,单个条件、多个条件,精确查询、模糊查询,查询结果排序,类似这些接口,我们该如何去实现,这就是本篇博客内容要总结的。
【核心及应用】
在Mybatis-Plus 2.1中,查询主要是通过核心类EntityWrapper实现的,而在Mybatis-Plus3.1中,则主要是通过QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类,用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件。
而前面博客中,引用的版本是2.1,所以,先在此基础上,简单举例实现各种查询。后期再对3.1版本做相关总结。
EntityWrapper wrapper=new EntityWrapper();
wrapper.setEntity(article);
https://baomidou.gitee.io/mybatis-plus-doc/#/quick-start
https://github.com/huzhiting/spring-boot-mybatis-plus-generator.git
eq(boolean condition, String column, Object params)
eq(String column, Object params)
//根据某列单个条件查询
wrapper.eq("site",article.getSite());
allEq(boolean condition, Map params)
allEq(Map params)
//多个条件组合查询
Map params=new HashMap<>();
params.put("site","LIFE");
params.put("cat_id","1");
wrapper.allEq(params);
like(boolean condition, String column, String value)
like(String column, String value)
// 模糊查询("%头条%"、"%头条"、"头条%")
article.setTitle("'头条'");
wrapper.like(true,"title",article.getTitle());
in(boolean condition, String column, String value)
in(String column, String value)
//in条件查询
wrapper.in("status","0,2");
orderBy(boolean condition, String columns)
orderBy(String columns)
orderBy(String columns, boolean isAsc)
orderBy(boolean condition, Collection columns, boolean isAsc)
...
//order by 排序
wrapper.orderBy("update_time",false);
【总结】
用Mybatis的时候,是可以使用生成的Example做一系列条件查询。每个实体下都有对应的一套Example,就会感觉代码冗余。
而Mybatis-Plus省去了这一套代码的生成,便可以将实体的各个属性都可以作为查询条件。
另外,Mybatis-Plus2.X和3.X版本还是挺大差异的,不过对于这些查询条件的运用,其实是一样的。根据官方文档或者是自己查看源代码实现,都可以快速实现。