MyBatisPlus 分页多表关联查询
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面
前言
MybatisPlus的BaseMapper提供的默认查询方法都是单表的,如果需要多表关联查询,同时还要支持分页,一个方案就是自己写 sql。
我看挺多人遇到这类查询都在 xml 里写 sql,并重新写了一堆查询条件的判断,其实没必要,我们可以使用注解来实现这一需求。
那如何在自定义 sql 语句中拼接 MyBatisPlus 的分页参数和查询条件呢?可以看看我下边的例子。
教程
关键在于 sql 字符串中的${ew.customSqlSegment},它是用来拼接LambdaQueryWrapper等查询条件包裹器对象最终输出的 sql 语句的。
java
@Mapper
public interface GroupVOMapper extends BaseMapper<GroupVO> {
String querySql = "select " +
"g.id as id, " +
"g.group_number as groupNumber, " +
"g.group_name as groupName, " +
"g.group_owner_id as groupOwnerId, " +
"g.group_owner_account as groupOwnerAccount, " +
"g.group_notice as groupNotice, " +
"g.group_cover as groupCover, " +
"g.join_type as joinType, " +
"g.status as status, " +
"g.create_time as createTime, " +
"(select u.nickname from tb_user u where g.group_owner_id = u.id ) as groupOwnerNickname, " +
"(select count(1) from tb_user_contact uc where uc.contact_type = 1 and uc.contact_id = g.id and uc.status = 1) as memberCount " +
"from tb_group g";
String wrapperSql = querySql + " ${ew.customSqlSegment}";
/**
* 分页查询
*/
@Select(wrapperSql)
Page<GroupVO> page(Page<?> page, @Param("ew") Wrapper<?> queryWrapper);
}
运行下,可以看到成功查询到接口

评论
0 条—
还没有评论,来说第一句