IService中的Lambda语法
实例:实现一个复杂条件查询的接口:
user_name用户名关键字,可以为空
age年龄关键字,可以为空
salary薪资关键字,在最大薪资(MaxSalary)和最小薪(MinSalary)资中间
正常的Mapper.xml中的写法:
<select id="selectUserByUserNameAndAgeAndSalery">
select * from user
<where>
<if test="userName != null">
userName = #{userName}
</if>
<if test="age != null">
and age = #{age}
</if>
<if test="MinSalary != null and MaxSalary != null">
and salary between #{MinSalary} and #{MaxSalary}
</if>
</where>
</select>
使用Lambda查询复杂条件
1.在controller中定义新的查询,查询条件过多时可以尝试将定义为一个查询类
查询类
package com.example.mybatisplus03.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(value = "UserQuery", description = "用户查询条件")
public class UserQuery {
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "年龄")
private Integer age;
@ApiModelProperty(value = "最大薪资")
private Double MaxSalary;
@ApiModelProperty(value = "最小薪资")
private Double MinSalary;
}
controller类
@ApiOperation("根据复杂条件批量查询用户")
@GetMapping
public List<User> selectListUser(UserQuery userQuery) {
List<User> users = userService.selectUserByUserNameAndAgeAndSalery(userQuery.getUserName(), userQuery.getAge(), userQuery.getMaxSalary(), userQuery.getMinSalary());
return users;
}
2.Service类
package com.example.mybatisplus03.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.mybatisplus03.entity.User;
import java.util.List;
public interface IUserService extends IService<User> {
void updateUserAgeById(Integer id, Integer age);
List<User> selectUserByUserNameAndAgeAndSalery(String userName, Integer age, Double maxSalary, Double minSalary);
}
3.ServiceImpl类
@Override
public List<User> selectUserByUserNameAndAgeAndSalery(String userName, Integer age, Double maxSalary, Double minSalary) {
List<User> users = lambdaQuery().eq(User::getUserName, userName)
.eq(User::getAge, age)
.between(User::getSalary, minSalary, maxSalary)
.list();
return users;
}
可以根据 需要选择要查询的条件:
one() :查询一个
count(): 符合条件的数量
list() :查询符合条件的多个
page() :分页查询
exist() :存不存在