IService中的Lambda语法——复杂查询

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() :存不存在

查询结果:

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L.2626

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值