- 引入依赖
<dependency> <groupId>com.github.yulichang</groupId> <artifactId>mybatis-plus-join-boot-starter</artifactId> <version>1.4.6</version> </dependency>
2.关联查询
baseMapper.selectJoinPage(page, StoreEntity.class, new MPJLambdaWrapper<StoreEntity>() .selectAll(StoreEntity.class) .select(DealerEntity::getDealerName) .leftJoin(DealerEntity.class, DealerEntity::getId, StoreEntity::getDistributorId) .eq(store.getStatus() != null, StoreEntity::getStatus, store.getStatus()));
说明:
- StoreEntity.class是最终返回的DTO
- new MPJLambdaWrapper()中的StoreEntity是主表查询的实体类
- .selectAll(StoreEntity.class)是查询主表的全部字段
- .select(DealerEntity::getDealerName)是查询字表的dealerName字段
- .leftJoin(DealerEntity.class, DealerEntity::getId, StoreEntity::getDistributorId)是表关联,DealerEntity.class是字表实体类,DealerEntity::getId关联字表的字段,StoreEntity::getDistributorId关联主表的字段
- .eq(store.getStatus() != null, StoreEntity::getStatus, store.getStatus())这个就是其他的条件查询啦,跟MP是一样的
以上执行SQL打印
select t.id, t.store_code, t.store_name, t.distributor_id, t.status, t.contact_person, t.contact_phone, t.store_location, t.position_lon, t.position_lat, t.create_by, t.create_time, t.update_by, t.update_time, t.dept_id, t.tenant_id, t.del_flag, # 这个是字表的字段 t1.dealer_name from tb_store t left join tb_dealer t1 on t1.id = t.distributor_id and t1.tenant_id = 1 where t.del_flag = '0' and t1.del_flag = '0' and t.tenant_id = 1 limit 10
跟写关联查询的sql是一样的