Java - Common methods of LambdaQueryWrapper

1. Check whether the jar package of mybatisPlus is imported into the project.

2. The servie layer and implementation class must be integrated with mybatisPlus

service inherits IService<>

Insert image description hereThe implementation class should inherit the implementation class ServiceImpl<mapper, entity class> of IService

Insert image description here

3. If you want some methods in mapper, mapper must inherit BaseMapper<entity class>

Insert image description here

4. To implement the method in the implementation class, there is no need to write a method in xml. Commonly used methods

Summarized as follows:

【1】Page

参数1是分页起始位置,一般是1,参数2:结束位置,    一般都是前端传过来的,查询的数量
Page<LandLossAllowance> page1 = new Page<LandLossAllowance>(参数1,参数2);
LambdaQueryWrapper<LandLossAllowance> queryWrapper = new LambdaQueryWrapper<>();
条件 eq 指的是相等
queryWrapper.eq(LandLossAllowance::getCountrySide,landLossAllowanceOption.getCountrySide());
执行page方法 page(参数1,参数2)
    参数1:上面的new的分页对象,参数2是lambda表达式查询条件
IPage<LandLossAllowance> iPage = page(page1, queryWrapper);

(1) The difference between PageHelper and IPage

Instructions:

PageHelper.startPage() and then write sql afterwards. The next sql works.
IPage needs to pass in the IPage implementation class Page object at the dao layer, which implements IPage.

the difference:

The internal principle of PageHelper is to assign the incoming page number and article number to the Page object, save it in a local thread ThreadLoacl, and then enter the interceptor of Mybatis.
    Then get the paging parameters saved in the local thread in the interceptor. Finally, the paging parameters are spliced ​​with the original sql and the internally defined sql to complete the sql paging processing.
    In the middle, it will be judged whether the type of sql is a query or a modification operation. If it is a query, it will enter the paging logic and determine whether the encapsulated Page object is null. If null, there will be no paging, otherwise it will be paging.

The internal principle of IPage is also based on interceptors, but this intercepts methods and parameters in the methods. This will also determine whether it is a query operation. If it is a query operation, the paging processing logic will be entered.
After entering the paging logic processing, the interceptor will obtain the parameters of the method through reflection to determine whether there is an implementation class of the IPage object. If it does not exist, no paging will be performed. If it exists, the parameter will be assigned to the IPage object.
Then perform splicing sql processing to complete the paging operation.
But using IPage requires injecting a bean interceptor and letting spring manage it. as follows. Otherwise the interception will not take place.

After using Ipage, you need to inject some configuration:

@Configuration
@MapperScan(value={"com.XX.**.mapper*"})
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        // 设置sql的limit为无限制,默认是500
        return new PaginationInterceptor().setLimit(-1);
    }
}

(2) Some definitions of commonly used lambda expressions

Insert image description here

com.baomidou.mybatisplus.core.conditions.query.QueryWrapper is a commonly used object in MybatisPlus framework to construct query conditions.

Using lambda expressions is more clear and concise:

 QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.lambda().eq(User::getName,"aa");
  queryWrapper.lambda().ge(User::getAge,20);

By default, multiple conditions are and connections: the SQL corresponding to the above writing method is: where name like '%aa%' and age >= 20

If you want to use or connection, the method is as follows:

queryWrapper.lambda().and(wq->{
    wq.like(User::getName,"aa");
    wq.or().like(User::getName,"bb);
});

Here is an extension of a scenario I encountered: what needs to be OR connected is all the elements in a collection:

List<String> nameList = Lists.newArrayList("aa","bb","cc");
String firstName = nameList.get(0);
nameList.remove(0);
queryWrapper.lambda().and(wq->{
    wq.like(User::getName,firstName);
    for(String name : nameList){
        wq.or().like(User::getName,name);
    }
});

The query condition
allEq
condition is encapsulated with Map

"name" -> "Zhang San"

“age” -> 20

public void testAllEq() {     QueryWrapper<User> queryWrapper = new QueryWrapper<>();     // Encapsulation condition     Map<String, Object> hashMap = new HashMap<>();     hashMap.put("name", "Zhang San" );     hashMap.put("age", 20);     queryWrapper.allEq(hashMap);     List<User> userList = userMapper.selectList(queryWrapper);     userList.forEach(user -> {         System.out.println(user);     }); } eq eq("column name", value) -> column name = value





 

 






    public List<Dict> listByDictCode(DictCode dictCode) {
        LambdaQueryWrapper<Dict> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Dict::getDictCode, dictCode.getCode())
               .eq(Dict::getEnabled, DictEnableEnum.VALID.getType());
        return this.baseMapper.selectList(wrapper);
    }
ne
ne("列名", 值) -> 列名 != 值

    public List<Dict> listByDictCode(DictCode dictCode) {
        LambdaQueryWrapper<Dict> wrapper = Wrappers.lambdaQuery();
        wrapper.ne(Dict::getDictCode, dictCode.getCode())
               .ne(Dict::getEnabled, DictEnableEnum.VALID.getType());
        return this.baseMapper.selectList(wrapper);
    }
gt
gt("age", 20) -> age > 20

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.gt(User::getAge, 20);            
        return this.baseMapper.selectList(wrapper);
    }
ge
ge("age", 20) -> age >= 20

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(User::getAge, 20);            
        return this.baseMapper.selectList(wrapper);
    }
lt
lt("age", 20) -> age < 20

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.lt(User::getAge, 20);            
        return this.baseMapper.selectList(wrapper);
    }
le
le("age", 21) -> age <= 21

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.le(User::getAge, 20);            
        return this.baseMapper.selectList(wrapper);
    }
between,notBetween
between("age", 18, 25) -> age BETWEEN 18 AND 25 ,年龄在18到25之间

notBetween means not between 18 and 25

    public List<User> userList() {         LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();         wrapper.between(User::getAge, 18,25);                         return this.baseMapper.selectList(wrapper);     } like,notLike like Matching value-> "%value%" fuzzy query





notLike fuzzy query does not match "%value%"

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
         wrapper.like(User::getName, "张");           
        return this.baseMapper.selectList(wrapper);
    }
likeLeft
likeLeft 匹配值 -> "%值"

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
         wrapper.likeLeft(User::getName, "张");           
        return this.baseMapper.selectList(wrapper);
    }
likeRight
likeRight 匹配值 -> "值%"

    public List<User> userList() {         LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();         wrapper.likeRight(User::getName, "Zhang");                    return this.baseMapper.selectList(wrapper);     } isNull null value query isNotNull non-null value query     public List<User> userList() {         LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();         wrapper.isNull(User::getName);         //wrapper.isNotNull(User::getName);                       return this .baseMapper.selectList(wrapper);     } in in("name", "Zhang San", "李思") -> name in ("Zhang San", "李思") User whose name is Zhang San or Li Si













notIn
notIn("name", "张三", "李思") -> name not in ("张三", "李思") User whose name is not Zhang San or Li Si

    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.in(User::getName, "张三","李四");
        //wrapper.in(User::getName, "张三","李四");           
        return this.baseMapper.selectList(wrapper);
    }
inSql、notInSql
public List<User> userList() {
    LambdaQueryWrapper<User> wrapper= new LambdaQueryWrapper<>();
    // SELECT id,name,email,age FROM user WHERE (age IN (select age from user where id = 1))
    wrapper.inSql(User::getAge, "select age from user where id = 1");
    return this.baseMapper.selectList(wrapper);
}
groupBy
分组

public List<User> userList() {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    wrapper.groupBy(User::getName);
    return this.baseMapper.selectList(wrapper);
}
orderBy、orderByAsc、orderByDesc
public List<User> userList() {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    // SELECT id,name,email,age FROM user ORDER BY name ASC,age DESC
    wrapper.orderBy(true, true, User::getName).orderBy(true, false, User::getAge);
    
    // SELECT id,name,email,age FROM user ORDER BY name ASC,age ASC
    wrapper.orderByAsc(User::getName, User::getAge);
 
    // SELECT id,name,email,age FROM user ORDER BY name DESC,age DESC
    wrapper.orderByDesc(User::getName, User::getAge);
 
    return this.baseMapper.selectList(wrapper);
}
or、and
    public List<User> userList() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
 
        // SELECT id,name,email,age FROM user WHERE (name = ? AND id = ?)
        wrapper.eq(User::getName, "张三").and().eq(User::getId,1);
 
        // SELECT id,name,email,age FROM user WHERE (name = ? OR id = ?)       
        wrapper.eq(User::getName, "张三").or().eq(User::getId,1);     
        return this.baseMapper.selectList(wrapper);
    }
这里说明一下or和and的问题

error code

public List<User> userList() {     LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();     wrapper.eq(User::getId,1);     wrapper.like(User::getName,"Zhang")            .or( )            .like(User::getEmail,"163")            .or()            .like(User::getAge,1); } The sql statement written according to the above writing method is as follows:
 








WHERE id = '1' 
    AND name LIKE '%张%'
    OR email LIKE '%163%'
    OR age LIKE '%1%'
This is obviously wrong. According to the order of mysql statement execution, it will be executed last. This will cause [ name like '%张%'] The or condition after the condition is established will be invalid, so the first condition does not play the role of and.

Solution
public List<User> userList() {     LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();     wrapper.eq(User::getId,1);     wrapper.and(wrapper->wrapper.like(User:: getName,"Zhang")                                 .or()                                 .like(User::getEmail,"163")                                 .or()                                 .like(User::getAge,1)                ); } The sql statement obtained in this way is as follows
 









WHERE id = '1' 
    AND (name LIKE '%张%'
    OR email LIKE '%163%'
    OR age LIKE '%1%')
This solves the problem. This problem is solved for new people in my company (including me) ) seems to have encountered this problem, let me explain it here

last
splices sql statement at the end

Note: last() has the risk of SQL injection, please use it with caution!

public List<User> userList() {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    // SELECT id,name,email,age FROM user WHERE (name = ? OR age = ?) limit 1
    wrapper.eq(User::getName, "张三").or().eq(User::getAge, 20).last("limit 1");
    return this.baseMapper.selectList(wrapper);
}
exists、notExists
public List<User> userList() {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
 
    // SELECT id,name,email,age FROM user WHERE (EXISTS (select name from user where age > ?))
    wrapper.exists("select name from user where age > 21");
 
    // SELECT id,name,email,age FROM user WHERE (NOT EXISTS (select name from user where age > ?))
    wrapper.notExists("select name from user where age > 21");
 
    return this.baseMapper.selectList(wrapper);
}

Guess you like

Origin blog.csdn.net/MinggeQingchun/article/details/131034200