注:本文代码样例及sql脚本均已上传至gitee:spring-boot-mybatis-plus学习
基本查询
/**
* id=?
*/
@Test
void selectById() {
User user = mapper.selectById(1087982257332887553L);
System.out.println(user);
}
/**
* id IN ( ?,?,? )
*/
@Test
void retrieveByIds() {
List<User> users = mapper.selectBatchIds(Arrays.asList(8,9,10));
users.forEach(System.out::println);
}
/**
* 根据map查询,key为column,value为具体的值
* name = ? AND age = ?
*/
@Test
void retrieveByMap() {
Map<String,Object> map = new HashMap<>();
map.put("name","大boss");
map.put("age","40");
List<User> users = mapper.selectByMap(map);
users.forEach(System.out::println);
}
条件构造器查询
地址: 条件构造器
/**
* 名字中包含雨并且年龄小于40
* name like '%雨%' and age<40
*/
@Test
void selectByWrapper1() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name","雨")
.lt("age",40);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
* name like '%雨%' and age between 20 and 40 and email is not null
*/
@Test
void selectByWrapper2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name","雨")
.between("age",20,40)
.isNotNull("email");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
* name like '王%' or age>=25 order by age desc,id asc
*/
@Test
void selectByWrapper3() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.likeRight("name","王")
.or().ge("age",25)
.orderByDesc("age")
.orderByAsc("id");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 创建日期为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 selectByWrapper4() {
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 = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* and中传入lambda
* <p>
* 名字为王姓并且(年龄小于40或邮箱不为空)
* name like '王%' and (age<40 or email is not null)
*/
@Test
void selectByWrapper5() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.likeRight("name","王").
and(wq -> wq.lt("age",40)
.or().isNotNull("email"));
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
* name like '王%' or (age<40 and age>20 and email is not null)
*/
@Test
void selectByWrapper6() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.likeRight("name","王").
or(wq -> wq.lt("age",40)
.gt("age",20)
.isNotNull("email"));
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* ( 年龄小于40或邮箱不为空)并且名字为王姓
* (age<40 or email is not null) and name like '王%'
*/
@Test
void selectByWrapper7() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.nested(wq -> wq.lt("age",40)
.or().isNotNull("email"))
.likeRight("name","王");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 年龄为30、31、34、35
*/
@Test
void selectByWrapper8() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.in("age",Arrays.asList(30,31,34,35));
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 只返回满足条件的其中一条语句即可 limit 1
*/
@Test
void selectByWrapper9() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.in("age",35)).last("limit 1");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
指定列与排除列
/**
* 查询指定列
* SELECT id,name FROM user WHERE (name LIKE ?)
*/
@Test
void selectPart1() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("id","name").like("name","雨");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
/**
* 排除指定列
* SELECT id,name,age,manager_id FROM user WHERE (name LIKE ?)
*/
@Test
void selectPart2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select(User.class,info -> !info.getColumn().equals("create_time") &&
!info.getColumn().equals("email")
).like("name","雨");
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
Condition处理参数
@Test
void testCondition(){
String name = "王";
String email = "";
//withOutCondition(name,email);
withCondition(name,email);
}
private void withOutCondition(String name,String email){
QueryWrapper<User> wrapper = new QueryWrapper<>();
if(StringUtils.isNotBlank(name)){
wrapper.like("name",name);
}
if(StringUtils.isNotBlank(email)){
wrapper.like("email",email);
}
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
private void withCondition(String name,String email){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(name),"name",name)
.like(StringUtils.isNotBlank(email),"email",email);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
以实体作为参数
/**
* WHERE name=? AND age=?
* 以实体为参数 和普通设置参数 互不干扰,都会存在,使用时需慎重
* 以实体为参数,默认是等值的,需要使用@TableField注解,并注明sqlCondition
*/
@Test
void selectByWrapperEntity(){
User user = new User();
user.setName("天乔巴夏");
user.setAge(20);
QueryWrapper<User> wrapper = new QueryWrapper<>(user);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
@TableField(value = "name",condition = sqlCondition.LIKE) //指定字段名
private String name;
AllEq的使用
@Test
void selectByWrapperAllEq(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
Map<String,Object> params = new HashMap<>();
params.put("name","天乔巴夏");
params.put("age",null); // age is null,可以通过 下面这句设置 false
wrapper.allEq(params,false);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
void selectByWrapperAllEq2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
Map<String,可以通过 下面这句设置 false
wrapper.allEq((k,v) -> !k.equals("name"),params,false);
List<User> users = mapper.selectList(wrapper);
users.forEach(System.out::println);
}
自定义查询
注解形式
public interface UserMapper extends BaseMapper<User> {
@Select("select * from user ${ew.customsqlSegment}")
List<User> selectAll(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
}
/**
* 测试自定义方法 注解
*/
@Test
void selectByCustomAnno(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","天乔巴夏");
List<User> users = mapper.selectAll(wrapper);
users.forEach(System.out::println);
}
xml形式
public interface UserMapper extends BaseMapper<User> {
List<User> selectAll2(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hyh.mybatisplus.mapper.UserMapper">
<select id="selectAll2" resultType="com.hyh.mybatisplus.entity.User">
select * from user ${ew.customsqlSegment}
</select>
</mapper>
其他的查询
/**
* 优雅返回指定字段的结果
*/
@Test
void selectByWrapperMaps1() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name",40)
.select("id","name");
List<Map<String,Object>> mapList = mapper.selectMaps(wrapper);
mapList.forEach(System.out::println);
}
/**
* 按照直属上级分组,查询每组的平均年龄、最大年龄、最小年龄。
* 并且只取年龄总和小于500的组。
*
* select avg(age) avg_age,min(age) min_age,max(age) max_age
* from user
* group by manager_id
* having sum(age) <500
*/
@Test
void selectByWrapperMaps2() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("avg(age) avg_age","min(age) min_age","max(age) max_age")
.groupBy("manager_id").having("sum(age)<{0}",500);
List<Map<String,Object>> mapList = mapper.selectMaps(wrapper);
mapList.forEach(System.out::println);
}
/**
* 只返回一列
*/
@Test
void selectByWrapperObjs() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("avg(age) avg_age",500);
List<Object> objects = mapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
/**
* 查个数
*/
@Test
void selectCount() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name","雨");
Integer cnt = mapper.selectCount(wrapper);
System.out.println(cnt);
}
/**
* 查一个实体
*/
@Test
void selectOne(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","天乔巴夏");
User user = mapper.selectOne(wrapper);
System.out.println(user);
}
/**
* lambda构造,编译时检查字段信息,防止误写
*/
@Test
void selectLambda(){
//LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
//LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> lambdaQuery = Wrappers.<User>lambdaQuery();
lambdaQuery.like(User::getName,"雨").lt(User::getAge,40);
// where name like '%雨%'
List<User> users = mapper.selectList(lambdaQuery);
users.forEach(System.out::println);
}