如何解决JPA 一对一映射在未找到子实体时创建多个查询
我有一个父实体“合同”,它与另一个实体“子合同”具有一对一的关系。有趣的是,映射字段 ('contract_number')id 不是主键外键,而是两个表中的唯一字段。合同也可能完全没有任何子合同。通过这种配置,我观察到每次合同没有子合同时,休眠都会生成 1 个额外的查询。我提起这种行为很奇怪。有没有办法阻止这些不必要的查询生成,或者我有什么问题。
下面是我的一段代码配置。
@Data
@Entity
@Table(name = "contracts")
public class Contracts implements Serializable {
@Id
@JsonIgnore
@Column(name = "id")
private String id;
@JsonProperty("contract_number")
@Column(name = "contract_number")
private String contractNumber;
@OneToOne(fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JsonProperty("crm_contracts")
@JoinColumn(name = "contract_number",referencedColumnName = "contract_number")
private ChildContract childContract ;
}
@Data
@NoArgsConstructor
@Entity
@Table(name = "child_contract")
@BatchSize(size=1000)
public class ChildContract implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@JsonProperty("id")
@Column(name = "id")
private String id;
@JsonProperty("contract_number")
@Column(name = "contract_number")
private String contractNumber;
}
请帮忙。
谢谢
解决方法
您可以使用 NamedEntityGraph
解决多个查询问题。
@NamedEntityGraph(name = "graph.Contracts.CRMContracts",attributeNodes = {
@NamedAttributeNode(value = "crmContract") })
在您的存储库方法中使用它
@EntityGraph(value = "graph.Contracts.CRMContracts",type = EntityGraphType.FETCH)
// Your repo method in repository
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。