Search code examples
javahibernatejpaspring-data-jpahibernate-mapping

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


My Question is when an null ability occur in one to one relation even my child class Primary Key same like parent class Primary Key So when Insert @PrimaryKeyJoinColumn on one to one relation in Insertion I have seen below Link Issue not-null property references a null or transient value in one to one relation

and when i Remove this tag n+1 issue resolved ...so how can i resolved it Please Help

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

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

in Parent Class Fields regarding one to one relations

    @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;
}

this is child class so how can i resolved both issue not null and n+1


Solution

  • Simply set optional=true in your OneToOne relationship like:

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