周末闲来无事,看到一篇博客,别人利用MyBatis-Plus实现了连表查询,然后自己平常也一直在用MyBatis-Plus,所以好奇,直接新建springboot-demo来亲自测试一下看看。以下就是一些关键步骤代码,敢兴趣可以自己新建项目测试一下,方便后续如果项目有需要用到,直接可以上手。

1、引入pom.xml

<dependency>
    <groupId>com.github.yulichang</groupId>
    <artifactId>mybatis-plus-join</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

2、新建两个实体类,并实现联表查询

在新建这两个实体类对应的Mapper层的时候,把原来的继承BaseMapper修改为继承MPJBaseMapper接口。实现联表查询的代码如下:
List<MybatisPlusTestVO> list =
mybatisPlusMapper.selectJoinList(MybatisPlusTestVO.class, new
MPJLambdaWrapper<Studio>() .selectAll(Studio.class)
.select(Course::getChannelId)
.selectAs(Course::getCourseTitle,MybatisPlusTestVO::getCourseName)
.leftJoin(Course.class, Course::getId, Studio::getCourseId)
.eq(Studio::getStatus,0)); list.forEach(System.out::println);
3、联表查询属性说明

*
selectAll():查询指定实体类的全部字段。

*
select():查询指定的字段,支持可变长参数同时查询多个字段,但是在同一个select中只能查询相同表的字段,所以如果查询多张表的字段需要分开写。

*
selectAs():字段别名查询,用于数据库字段与接收结果的dto中属性名称不一致时转换。

*
leftJoin():左连接,其中第一个参数是参与联表的表对应的实体类,第二个参数是这张表联表的ON字段,第三个参数是参与联表的ON的另一个实体类属性。

*
注意:默认主表别名是t,其他的表别名以先后调用的顺序使用t1、t2、t3以此类推。

4、分页查询

        要实现分页查询,得先加入分页拦截器,如下:
@Configuration public class MybatisPlusPageConfig { @Bean public
MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor
interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new
PaginationInnerInterceptor(DbType.H2)); return interceptor; } }
分页查询代码如下:
public String page() { IPage<MybatisPlusTestVO> studioPage =
mybatisPlusMapper.selectJoinPage( new Page<MybatisPlusTestVO>(2,10),
MybatisPlusTestVO.class, new MPJLambdaWrapper<Studio>()
.selectAll(Studio.class) .select(Course::getChannelId)
.selectAs(Course::getCourseTitle, MybatisPlusTestVO::getCourseName)
.leftJoin(Course.class, Course::getId, Studio::getCourseId)
.orderByAsc(Studio::getId));
studioPage.getRecords().forEach(System.out::println); return null; }
5、总结

        萝卜青菜各有所爱,在业务场景不复杂的情况下,使用这种联表查询还是可以的,具体是否需要引入项目中去,还是得自己考量一下。

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信