MyBatis-Plus多表联查写法
前言
收获大佬封装的一个jar包,可以支持MyBatis-Plus多表联查,特此分享。
一、引依赖
注意: mybatis plus version >= 3.4.0
com.github.yulichang mybatis-plus-join 1.2.4
二、使用方法
mapper继承MPJBaseMapper (必选)
service继承MPJBaseService (可选)
serviceImpl继承MPJBaseServiceImpl (可选)
三、(实战)多表查询
MPJLambdaWrapper<Map> mpjLambdaWrapper = new MPJLambdaWrapper();mpjLambdaWrapper.select(ChatRecord::getId,ChatRecord::getRedMoney) .select(OfShopMembers::getUsablePoint) .select(ChatMultiList::getName).leftJoin(OfShopMembers.class,OfShopMembers::getId,ChatRecord::getId).leftJoin(ChatMultiList.class,ChatMultiList::getId,ChatRecord::getMultiId).eq(ChatRecord::getMemberId,3213);List list = chatRecordMybatisJoinMapper.selectJoinList(Map.class, mpjLambdaWrapper);
对应查询语句
SELECT t.id,t.red_money,t1.username,t2.name FROM chat_record t LEFT JOIN of_shop_members t1 ON (t1.id = t.id) LEFT JOIN chat_multi_list t2 ON (t2.id = t.multi_id) WHERE (t.member_id = 3213)
参数说明
select:表示查询的指定字段,一个select只能查一个表的
2、leftJoin:
第一个参数: 参与连表的实体类class
第二个参数: 连表的ON字段,这个属性必须是第一个参数实体类的属性
第三个参数: 参与连表的ON的另一个实体类属性
3、默认主表别名是t,其他的表别名以先后调用的顺序使用t1,t2,t3…
四、(实战)多表分页查询
MPJLambdaWrapper<Map> mpjLambdaWrapper = new MPJLambdaWrapper(); mpjLambdaWrapper.select(ChatRecord::getId,ChatRecord::getRedMoney) .select(OfShopMembers::getUsablePoint) .select(ChatMultiList::getName) .leftJoin(OfShopMembers.class,OfShopMembers::getId,ChatRecord::getId) .leftJoin(ChatMultiList.class,ChatMultiList::getId,ChatRecord::getMultiId) .eq(ChatRecord::getMemberId,3213) .orderByDesc(ChatRecord::getAddTime); Page page = new Page(1,2); IPage<Map> mapIPage = chatRecordMybatisJoinMapper.selectJoinPage(page, Map.class, mpjLambdaWrapper);
对应查询语句
SELECT t.id,t.red_money,t1.usable_point,t2.name FROM chat_record t LEFT JOIN of_shop_members t1 ON (t1.id = t.id) LEFT JOIN chat_multi_list t2 ON (t2.id = t.multi_id)WHERE (t.member_id = 3213) ORDER BY t.add_time DESC LIMIT 2
来源地址:https://blog.csdn.net/xujx321/article/details/129708003