n+1 问题与延迟加载一对一关系

n+1 issue in one to one relation with Lazy Loading

我的问题是,即使我的 child class 主键与 parent class 主键相同,所以当插入 @插入中一对一关系的 PrimaryKeyJoinColumn 我在下面看到 Link 问题 not-null property references a null or transient value in one to one relation

当我删除此标签时,第 n+1 个问题已解决...那么我该如何解决请帮助

private SiteSecurity siteSecurity;
private SiteDetails details;
private SiteAvr avr;
private SiteRectifier rectifier;

@OneToOne( fetch = FetchType.LAZY, mappedBy = "site")
@PrimaryKeyJoinColumn

in Parent Class 关于一对一关系的字段

    @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "site"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

public void setId(Integer id) {
    this.id = id;
}

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Site getSite() {
    return site;
}

public void setSite(Site site) {
    this.site = site;
}

这是 child class 那么我该如何解决 not null 和 n+1 这两个问题

只需在您的 OneToOne 关系中设置 optional=true,例如:

@OneToOne(fetch = FetchType.LAZY, optional=true)
@PrimaryKeyJoinColumn
public Site getSite() {
    return site;
}

为避免 n+1 问题,确保一对一关系与另一个同步 table 如果站点 Table 有一行,那么另一个一对一关系 table 有反对他们,这个注释 @PrimaryKeyJoinColumn 在他们身上...

在我的例子中,这个策略可以避免 n+1 问题

请通过这个点赞也简单说明一下一对一关系Post