首页 > 解决方案 > Spring JPA 投影 - 在嵌套对象列表中选择特定列

问题描述

为什么我收到以下错误:

查询指定连接提取,但提取关联的所有者不在选择列表中

当我尝试获取 ID 列表时?

@Query("SELECT at.id FROM Template at " +
            "WHERE at.shipper.id = :companyId " +
            "AND at.isActive = true")
    @EntityGraph(attributePaths = {"shipper"})
    List<Long> findTemplateIdsByCompanyId2(Long companyId, Pageable pageable);

但是当我想获取对象列表时 - 一切都好吗?

@Query("SELECT at FROM Template at " +
            "WHERE at.shipper.id = :companyId " +
            "AND at.isActive = true")
    @EntityGraph(attributePaths = {"shipper"})
    List<Template > findTemplateIdsByCompanyId2(Long companyId, Pageable pageable);

Template实体与字段有关系OneToOne 和与字段有关系shipperOneToManywarehouse

标签: spring-bootspring-data-jpa

解决方案


如果您不获取实体,则需要加入查询,应该这样做:

SELECT at.id FROM Template at JOIN at.Shipper s WHERE s.id = :companyId and at.isActive = true

推荐阅读