Hibernate JOIN ON生成无效查询

时间:2016-11-04 10:09:57

标签: hibernate jpa

我需要列出所有Product条记录,无论它们是否具有相应的ForeignProductInfoProduct没有提及ForeignProductInfo

我正在使用这个JPA查询:

@Query("select distinct fpi from Product pp "
        + "left join fetch ForeignProductInfo fpi on fpi.partner.id = :partnerId "
        + "left join fetch fpi.product p ") 
public List<ForeignProductInfo> loadAllForPartner(@Param("partnerId") Long partnerId);

这一直有效,直到我添加第二个连接(以避免在访问ForeignProductInfo.product时选择n + 1)。然后它生成这个SQL:

SELECT 
    foreignpro1_.id AS id1_7_0_,
    product2_.id AS id1_12_1_,
    productsub3_.id AS id1_18_2_,
    productgro4_.id AS id1_14_3_,
    foreignpro1_.code AS code2_7_0_,
    foreignpro1_.name AS name3_7_0_,
    foreignpro1_.partner_id AS partner_4_7_0_,
    foreignpro1_.product_id AS product_5_7_0_,
    product2_.a AS a2_12_1_,
    product2_.b AS b3_12_1_,
    product2_.comment AS comment4_12_1_,
    product2_.conversionMethod AS conversi5_12_1_,
    product2_.diaMax AS diaMax6_12_1_,
    product2_.diaMin AS diaMin7_12_1_,
    product2_.len AS len8_12_1_,
    product2_.mu AS mu9_12_1_,
    product2_.name AS name10_12_1_,
    product2_.nameLang1 AS nameLan11_12_1_,
    product2_.nameLang2 AS nameLan12_12_1_,
    product2_.productSubGroup_id AS product15_12_1_,
    product2_.surfaceMax AS surface13_12_1_,
    product2_.surfaceMin AS surface14_12_1_,
    productsub3_.name AS name2_18_2_,
    productsub3_.productGroup_id AS productG3_18_2_,
    productgro4_.name AS name2_14_3_,
    productgro4_.seq AS seq3_14_3_
FROM
    Product product0_
        LEFT OUTER JOIN
    ForeignProductInfo foreignpro1_ ON (foreignpro1_.partner_id = 3);

如您所见,第二个JOIN缺失并导致异常:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'product2_.id' in 'field list'

编辑:ForeignProductInfo每个ProductPartner的组合只有一条或一条记录。

@Entity
public class ForeignProductInfo {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private Partner partner;

    @ManyToOne
    private Product product;

    @Column(length=50)
    @Size(max=50)
    private String code;

    @Column(length=200)
    @Size(max=200)
    private String name;
    ...
}

1 个答案:

答案 0 :(得分:0)

我无法在3天内解决这个问题。这是SQL中最简单的事情,但似乎无法在JPA中实现。还尝试了标准API,但不能进行条件提取,只能有条件地加入。

我最后走了一个Product列表并逐个加载ForeignProductInfo。 :(然后抛弃了JPA并使用了纯SQL。