@MybatisPlus自定义sql多表关联分页条件查询
网上对于多表分页查询的mp描述不是很清楚,我在这里重新写一篇文章。
需要实现的sql是两表关联条件查询
select um.`nickname` ,aa.`comment_counts`,aa.`gmt_create`,
aa.`id`,aa.`summary`,aa.`title`,aa.`view_counts`,aa.`weight`
from atai_article aa join ucenter_member um
on aa.`author_id`=um.`id`
where aa.`title` like '%v%' limit 0 ,1;
查询效果
涉及数据库 atai_article和ucenter_member,ucenter_member不展示只需要关联查询nickname即可。
关键代码
Page pageArticle = new Page<>(current,limit);
IPage result = ataiArticleService.findAllArticleCondition(pageArticle,articleQuery);
@ApiOperation(value = "分页条件查询文章列表")
@PostMapping("pageArticleCondition/{current}/{limit}")
public R findAllArticleCondition(@PathVariable long current, @PathVariable long limit,
@RequestBody(required = false) ArticleQuery articleQuery) {
Page pageArticle = new Page<>(current,limit);
IPage result = ataiArticleService.findAllArticleCondition(pageArticle,articleQuery);
List list = result.getRecords();
//调用service的方法实现查询所有的操作
return R.success().data("total",result.getTotal()).data("records",list);
}
public interface AtaiArticleService extends IService {
IPage findAllArticleCondition(Page pageArticle, ArticleQuery wrapper);
}
@Service
public class AtaiArticleServiceImpl extends ServiceImpl implements AtaiArticleService {
@Override
public IPage findAllArticleCondition(Page pageArticle, ArticleQuery wrapper) {
IPage articleFrontVos = baseMapper.findAllArticleCondition(pageArticle,wrapper);
return articleFrontVos;
}
}
关键代码,起别名articleQuery在xml中取数据
@Param("articleQuery") ArticleQuery articleQuery
public interface AtaiArticleMapper extends BaseMapper {
IPage findAllArticleCondition(@Param("page")Page page, @Param("articleQuery") ArticleQuery articleQuery);
}
关键代码,使用articleQuery取数据
and t1.title like "%"#{articleQuery.title,jdbcType=VARCHAR}"%"
ArticleFrontVo
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="ArticleFrontVo对象", description="文章")
public class ArticleFrontVo implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "文章ID")
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "摘要")
private String summary;
@ApiModelProperty(value = "标题")
private String title;
@ApiModelProperty(value = "评论数")
private Integer commentCounts;
@ApiModelProperty(value = "浏览数")
private Integer viewCounts;
@ApiModelProperty(value = "权重")
private Integer weight;
@ApiModelProperty(value = "作者名称")
private String nickname;
@ApiModelProperty(value = "标签列表")
private String tag;
@ApiModelProperty(value = "创建时间")
private Date gmtCreate;
}
ArticleQuery
@Data
public class ArticleQuery {
@ApiModelProperty(value = "文章标题,模糊查询")
private String title;
@ApiModelProperty(value = "查询开始时间", example = "2019-01-01 10:10:10")
private String begin;//注意,这里使用的是String类型,前端传过来的数据无需进行类型转换
@ApiModelProperty(value = "查询结束时间", example = "2019-12-01 10:10:10")
private String end;
}
使用的是swagger进行接口测试
正确检索出数据