如何解决具有一对多映射的 Hibernate FetchMode.JOIN
有两个实体 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;
}
InvoiceHdrPK
@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",@JoinColumn(name = "invoice_type",referencedColumnName = "invoice_type",@JoinColumn(name = "company_id",referencedColumnName = "company_id",@JoinColumn(name = "invoice_year",referencedColumnName = "invoice_year",})
private InvoiceHeader invoiceHeader;
}
InvoiceDetailPK
@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 我正在尝试使用 findAll(Specification,pageable) 和 FetchMode.JOIN 获取发票以避免 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) 私有集合项 = 新 HashSet();
,您似乎使用了类似于此 select b from A a join a.b b join fetch a.c
的查询。要点是,您加入了一些关联,这些关联您从未在 select 子句中通过父项引用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。