简体   繁体   中英

@OneToMany is giving null value in spring data jpa

public class Enterprise{
.....
    @OneToMany(mappedBy = "enterprise", fetch = FetchType.EAGER)
    private List<Organization> organizations;
.....
}

public class Organization{
....
    @ManyToOne
    @JoinTable(name = "enterprise_organization_map", joinColumns = {
            @JoinColumn(name = "organization_id") }, inverseJoinColumns = { @JoinColumn(name = "enterprise_id") })
    private Enterprise enterprise;
....
}

When I tried to fetch Enterprise, I am not getting the mapped organizations. its returning null.

//print statement

Enterprise with Organizations:Enterprise [enterpriseId=13, enterpriseName=xyz, organizations=null]

Can anyone please help me here.

Bidirectional one-to-many associations required helper methods to 'link' both entities, see the manual :

Whenever a bidirectional association is formed, the application developer must make sure both sides are in-sync at all times. The addPhone() and removePhone() are utilities methods that synchronize both ends whenever a child element is added or removed.

So you have to add to Enterprise at least one such method and use it when you add Organization to Enterprise :

public Enterprise addOrganization(Organization organization) {

    organization.setEnterprise(this);
    this.organizations.add(organization);
    return this;
}

I don't see such method in your code. I think this is the reason of your problem.

Additional useful info about one-to-many you can find here: Best Practices for Many-To-One and One-To-Many Association Mappings .

问题出在toString()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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