亲宝软件园·资讯

展开

Springboot分页带条件查询

低调码农哥! 人气:3

完整案例:

SpringBoot + laypage分页 + 模糊查询 完整案例

下面在通过实例代码介绍下springboot +mybatis 使用PageHelper实现分页并带条件模糊查询功能,内容如下所示:

调用接口Controller类

@ApiOperation("查询列表")
    @PostMapping("/selectList")
    public Result selectList(@RequestBody User_InfoListRequest userInfo ) {
        Page page = PageHelper.startPage(userInfo.pageNum,userInfo.pageSize); //这行是重点(放在方法第一行)表示从pageNum页开始,每页pageSize条数据
        List<User_info> _list= userService.selectList(userInfo);//返回集合和分页之前不要有其它代码,这两行上下要紧靠近
        PageInfo pageInfo = new PageInfo<>(_list);
        return  Result.SUCCESS( pageInfo);
    }
package com.xj.demo.model.Request;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
public class User_InfoListRequest extends  PageRequest  {
    @ApiModelProperty(value = "学生姓名")
    public String uname;
    @ApiModelProperty(value = "学生年龄")
    public int uage;
}
import lombok.Data;
/**
 * 分页请求request基类
 */
@Data
public class PageRequest  {
    @ApiModelProperty(value = "当前页码")
    public Integer pageNum;
    @ApiModelProperty(value = "分页大小")
    public Integer pageSize;

定义接口,注意红色显示部分

package com.xj.demo.mapper;

import com.github.pagehelper.Page;
import com.xj.demo.model.Request.UserEditRequest;
import com.xj.demo.model.Request.User_InfoListRequest;
import com.xj.demo.model.Response.UserInfoResponse;
import com.xj.demo.model.entity.User_info;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface User_infoMapper {
    // 查询列表
     List<User_info> selectList(@Param("userInfo")  User_InfoListRequest userInfo);
    
}

实现接口service

package com.xj.demo.service;

import com.github.pagehelper.Page;
import com.xj.demo.mapper.User_infoMapper;
import com.xj.demo.model.Request.UserEditRequest;
import com.xj.demo.model.Request.User_InfoListRequest;
import com.xj.demo.model.Response.UserInfoResponse;
import com.xj.demo.model.entity.User_info;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class User_infoService implements User_infoMapper {
    @Autowired
    private  User_infoMapper uMapper;
    @Override
    public List<User_info> selectList(User_InfoListRequest userInfo) {
        return uMapper.selectList(userInfo);
    }
 
   
}

mapper中sql语句uname进行模糊查询和年龄完全匹配

<!---查询列表-->
    <select id="selectList" resultType="User_info">
    select * from User_info where 1=1
     <if test="userInfo!=null">
        <if test="userInfo.uname!=null and userInfo.uname!='' ">
             and uname like '%' #{userInfo.uname} '%'
        </if>

         <if test="userInfo.uage!=0">
             and uage = #{userInfo.uage}
         </if>
     </if>
     order by create_time desc
    </select>

使用postman进行接口测试

加载全部内容

相关教程
猜你喜欢
用户评论