MyBatis-Plus进行多表关联查询:使用MyBatis-Plus的SQL构建器 ( MPJLambdaWrapper )
还可以使用MyBatis-Plus的SQL构建器进行多表关联查询,例如:
下面详细举一个,联表查询产品和厂商的例子:
(1)引入相关依赖项
<!-- 引入mybatis-plus联表查询相关依赖项 -->
<!-- MVNW pom格式 -->
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join</artifactId>
<version>1.2.4</version>
</dependency>
<!-- Gradle 格式 -->
implementation 'com.github.yulichang:mybatis-plus-join:1.2.4'
(2)相关实体类
/**
* 产品实体
*/
@Data
@TableName(value = "t_product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
/** 本表id */
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
/** 产品编码code */
private String code;
/** 产品名称 */
private String name;
/** 厂商编码code */
private String factoryCode;
}
/**
* 厂商实体
*/
@Data
@TableName(value = "t_factory")
public class Factory implements Serializable{
private static final long serialVersionUID = 1L;
/** 本表id */
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
/** 厂商编码code */
private String code;
/** 厂商名称 */
private String name;
}
/**
* 联表查询结果类
*/
@Data
public class ProductVO implements Serializable {
/** 产品编码code */
private String code;
/** 产品名称 */
private String name;
/** 厂商编码code */
private String factoryCode;
/** 厂商名称 */
private String factoryName;
}
(3)以产品为为主的Mapper层
特别注意集成 MPJBaseMapper,泛型为 Product 实体
/**
* @Description: Mapper层
* @Author: mc 2023/6/18 11:10
*/
@Repository
public interface ProductMapper extends MPJBaseMapper<Product> {
}
(4)业务逻辑实现层进行相关查询及逻辑处理
不做更多查询条件约束,数据库内产品表共10条数据,测试普通查询以及联表查询
注意联表查询时,selectJoinList()方法第一个参数为查询结果集映射的实体类,本处为ProductVO.class
/**
* @Description: 产品相关业务逻辑实现层
* @Author: mc 2023/6/18 11:14
*/
@Slf4j
@Service
public class ProductService {
@Autowired
private ProductMapper productMapper;
public List<ProductVO> getProductInfo() {
// 测试单表查询
List<Product> one = productMapper.selectList(null);
log.debug("单表查询,查询返回结果为:{}", one);
// 测试联表查询
List<ProductVO> two = productMapper.selectJoinList(ProductVO.class,
new MPJLambdaWrapper<Product>()
.select(Product::getCode, Product::getName)
.selectAs(Factory::getCode, ProductVO::getFactoryCode)
.selectAs(Factory::getName, ProductVO::getFactoryName)
.leftJoin(Factory.class, Factory::getCode, Product::getFactoryCode)
);
log.debug("联表查询,查询返回结果为:{}", two);
return null;
}
}
// 其他方面
selectAll() // 可以查全部参数;
select() // 查询字段,一个括号内仅能查一个实体,如需要查询多个表的字段,将有多个select();
selectAs() // 相当于取别名,为了数据表内字段名称和结果集实体名称一致;
leftJoin() //联结多个表,将有多个leftJoin(),方法3个参数:联入表实体,联入表关系字段,原表关系字段;
(5)查询结果
单表查询:
联表查询 :