MybatisPlus自定义多表Sql分页查询

MybatisPlus自定义多表Sql分页查询

  • 自定义sql分页的步骤
  • 使用的MybatisPlus的版本
  • 分页工具可以自己定义
  • 入参实体
  • 出参实体
    • 这是接口实现的代码
    • 这里是Mapper的代码

自定义sql分页的步骤

  1. 第一个参数必须为分页的参数IPage,后面参数为QueryWrapper

使用的MybatisPlus的版本

<properties><mybatis.plus.version>3.1.0mybatis.plus.version>properties>
     <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-coreartifactId>
            <version>${mybatis.plus.version}version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>${mybatis.plus.version}version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-annotationartifactId>
            <version>${mybatis.plus.version}version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-extensionartifactId>
            <version>${mybatis.plus.version}version>
        dependency>

分页工具可以自己定义

//
@Slf4j
@Data
@ToString
@ApiModel(description = "分页请求对象")
public class PageReq<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "页码", required = true, example = "1")
    private int pageNo;
    @ApiModelProperty(value = "页大小", required = true, example = "20")
    private int pageSize;
    @ApiModelProperty(value = "参数实体")
    private T t;

    /**
     * 获取mysql的limit的开始位置
     *
     * @return
     */
    public int getMyStart() {
        return (pageNo - 1) * pageSize;
    }

    public static <T> PageReq<T> getPageReq(String json, Class<T> objClass) {
        ObjectMapper mapper = JSONUtils.getMapperInstance();
        JsonNode root = null;
        PageReq<T> page = null;
        try {
            root = mapper.readTree(json);
            page = new PageReq<T>();
            page.setPageNo(root.get("pageNo").asInt());
            page.setPageSize(root.get("pageSize").asInt());
            JsonNode tNode = root.get("t");
            if (tNode != null) {
                T t = JSONUtils.jsonToObject(root.get("t"), objClass);
                page.setT(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("json string to JsonNode error,please check json string!json:" + json, e);
            throw new RuntimeException("json string to JsonNode error,please check json string!");
        }
        return page;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof PageReq)) {
            return false;
        } else {
            PageReq other = (PageReq) o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                Object this$pageNo = this.getPageNo();
                Object other$pageNo = other.getPageNo();
                if (this$pageNo == null) {
                    if (other$pageNo != null) {
                        return false;
                    }
                } else if (!this$pageNo.equals(other$pageNo)) {
                    return false;
                }

                Object this$pageSize = this.getPageSize();
                Object other$pageSize = other.getPageSize();
                if (this$pageSize == null) {
                    if (other$pageSize != null) {
                        return false;
                    }
                } else if (!this$pageSize.equals(other$pageSize)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof PageReq;
    }

    @Override
    public int hashCode() {
//		int PRIME = true;
        int result = 1;
        Object $pageNo = this.getPageNo();
        result = result * 59 + ($pageNo == null ? 43 : $pageNo.hashCode());
        Object $pageSize = this.getPageSize();
        result = result * 59 + ($pageSize == null ? 43 : $pageSize.hashCode());
        return result;
    }

    @Override
    public String toString() {
        return "PageReq(pageNo=" + this.getPageNo() + ", pageSize=" + this.getPageSize() + ")";
    }

}

入参实体

@Data
public class TeamPageReq {
    @ApiModelProperty("用户名")
    private String userName;
    @ApiModelProperty("电话号码")
    private String phone;

}

出参实体

@Data
public class TeamRes {

    private BigDecimal achievement;

    private String id;

    private String userName;

    private String phone;

   private String phone;

   private String vipNum;

   private String achievement;

   private String parent;

}
@RequestMapping("/teamApi")
public class TeamController {

    @Autowired
    private ITeamService teamService;

    @ApiOperation(value = "团队列表查询", notes = "团队列表查询")
    @PostMapping("/findTeamPage")
    public ResponseVo<Page<TeamRes>> findOrderPage(@RequestBody PageReq<TeamPageReq> teamReqPage) {
        return new ResponseVo(ResponseEnum.OK, teamService.findTeamPage(teamReqPage));
    }


}
public interface ITeamService extends IService<TeamEntity>{
    IPage<TeamRes> findTeamPage(PageReq<TeamPageReq> teamReqPage);
}

这是接口实现的代码

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcr.backstage.entity.TeamEntity;
import com.zcr.backstage.mapper.TeamMapper;
import com.zcr.backstage.req.TeamPageReq;
import com.zcr.backstage.res.TeamRes;
import com.zcr.backstage.service.ITeamService;
import com.zcr.common.business.BusinessException;
import com.zcr.common.business.ResponseEnum;
import com.zcr.common.manager.ISessionManager;
import com.zcr.common.utils.StringUtils;
import com.zcr.common.vo.PageReq;
import com.zcr.common.vo.UserJwtRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, TeamEntity> implements ITeamService {
/**
这段代码的作用是从数据库中查询符合条件的团队信息,并以分页的形式返回结果。具体实现如下:

1. 从前端传入的参数中获取用户名和电话号码。

2. 创建一个QueryWrapper对象,用于构建查询条件。

3. 如果用户名不为空,则使用like查询,查询条件为u.user_name字段包含用户名。

4. 如果电话号码不为空,则使用like查询,查询条件为u.phone字段包含电话号码。

5. 创建一个Page对象,用于分页查询,设置当前页码和每页记录数。

6. 调用baseMapper的pageTeamInfo方法进行分页查询,传入Page对象和QueryWrapper对象作为参数。

7. 将查询结果封装成IPage对象并返回。
*/
    @Override
    public IPage<TeamRes> findTeamPage(PageReq<TeamPageReq> teamReqPage) {

        String userName = teamReqPage.getT().getUserName();
        String phone = teamReqPage.getT().getPhone();
        QueryWrapper teamResQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            teamResQueryWrapper.like("u.user_name", userName);
        }
        if (StringUtils.isNotBlank(teamReqPage.getT().getPhone())) {
            teamResQueryWrapper.like("u.phone", phone);
        }
        Page<TeamRes> page = new Page<>();
        page.setCurrent(teamReqPage.getPageNo());
        page.setSize(teamReqPage.getPageSize());

        IPage<TeamRes> resPage = baseMapper.pageTeamInfo(page, teamResQueryWrapper);

        return resPage;
    }
}

这里是Mapper的代码

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeamMapper extends BaseMapper<TeamEntity> {
/**
这段代码是一个MyBatis Plus的查询语句,查询了数据库表z_team和z_user的多个字段信息,并通过INNER JOIN将两个表关联起来。
其中,${ew.customSqlSegment}是MyBatis Plus的动态SQL语法,用于在运行时根据条件动态生成SQL语句。
@Select(sql)表示使用该SQL语句进行查询。
最后,将查询结果封装成IPage类型的分页对象,并通过@Param(Constants.WRAPPER)将查询条件传递给方法。
*/
 String sql = "SELECT\n" +
            "\tu.id,\n" +
            "\tu.user_name,\n" +
            "\tu.phone,\n" +
            "\tt.vip_num,\n" +
            "\tt.achievement,\n" +
            "\tt.parent\n" +
            "FROM\n" +
            "\tz_team t\n" +
            "\tINNER JOIN z_user u ON u.id = t.user_id \n" +
            "\tAND u.del_flag =0 ${ew.customSqlSegment}";
//Constants.WRAPPER 也可以写成ew
    @Select(sql)
    IPage<TeamRes> pageTeamInfo(Page<TeamRes> page, @Param(Constants.WRAPPER) QueryWrapper queryWrapper);
}

你可能感兴趣的:(sql,mybatis,java,spring,boot,log4j)