繁体   English   中英

Hibernate FetchMode.JOIN 与一对多映射

[英]Hibernate FetchMode.JOIN with one to many mapping

有两个实体 InvoiceHeader 和 InvoiceDetail 具有一对多映射,如下所示。

发票头

@Entity
@Table(name = "view_invoice_hdr")
@IdClass(InvoiceHdrPK.class)
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class InvoiceHeader{
  
  ....
  
  @OneToMany(mappedBy = "invoiceHeader", fetch = FetchType.EAGER)
  @Fetch(value = FetchMode.JOIN)
  private List<InvoiceDetail> items;
} 

发票HdrPK

@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class InvoiceHdrPK implements Serializable {

    private String invoiceNumber;
    private InvoiceSource invoiceSource;
    private InvoiceType invoiceType;
    private Long companyId;
    private Integer invoiceYear;
}

同样InvoiceDetail

@Entity
@Table(name = "view_inv_dtl")
@IdClass(InvoiceDetailPK.class)
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class InvoiceDetail{
  
  ....
  
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns(value = {
            @JoinColumn(name = "invoice_number", referencedColumnName = "invoice_number", insertable = false, updatable = false),
            @JoinColumn(name = "invoice_source", referencedColumnName = "invoice_source", insertable = false, updatable = false),
            @JoinColumn(name = "invoice_type", referencedColumnName = "invoice_type", insertable = false, updatable = false),
            @JoinColumn(name = "company_id", referencedColumnName = "company_id", insertable = false, updatable = false),
            @JoinColumn(name = "invoice_year", referencedColumnName = "invoice_year", insertable = false, updatable = false),
    })
    private InvoiceHeader invoiceHeader;
} 

发票明细PK

@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class InvoiceDetailPK implements Serializable {

    private String invoiceNumber;
    private InvoiceSource invoiceSource;
    private InvoiceType invoiceType;
    private BigDecimal rate;
    private Long itemNo;
    private Long companyId;
    private Integer invoiceYear;

}

这两个实体都不是数据库级别的实际表,而是作为视图维护。

使用 JPA我正在尝试使用带有FetchMode.JOINfindAll(Specification, pageable)来获取发票以避免n+1查询问题。

但得到异常

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list...

那么我该如何解决这个问题,我错过了什么?

也许你使用 Set 而不是 List @OneToMany(mappedBy = "invoiceHeader", fetch = FetchType.EAGER) @Fetch(value = FetchMode.JOIN) private Set items = new HashSet<>();

似乎您使用类似于此select b from A a join ab b join fetch a.c的查询。 要点是,您加入获取一些您从未通过 select 子句中的父项引用的关联。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM