【问题标题】:@OneToMany is giving null value in spring data jpa@OneToMany 在春季数据 jpa 中给出空值
【发布时间】:2017-08-17 20:32:45
【问题描述】:
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;
....
}

当我尝试获取 Enterprise 时,我没有获取映射的组织。它返回 null。

//打印语句

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

谁能帮帮我。

【问题讨论】:

  • 你是如何插入的,又是如何获取的?
  • @AmerQarabsa 使用 JpaRepository。组织组织=新组织(); organization.setOrganizationName("XYZSoftware");组织.setEnterprise(企业);组织 savedOrganization = this.repository.save(organization); System.out.println("企业与组织:" + savedOrganization.getEnterprise().getOrganizations()); System.out.println("Enterprise with Organizations:" + this.enterpriseRepository.findOne(enterprise.getEnterpriseId‌​()));
  • 你能显示organizations的getter吗?
  • @LudovicGuillaume getter 只是普通的 getter。在变量级别,我绘制了组织图。 @OneToMany(mappedBy = "enterprise", fetch = FetchType.EAGER) 私有列表 组织;如果我从 Enterprise.toString() 中删除组织,我就能得到它。现在的问题是,Enterprise->Organization->Enterprise->.... 递归对象构建正在发生。我只想获得一次对象。如何解决?即,只有企业->组织。
  • 我们需要更多信息。在哪种情况下您会遇到递归问题?简单打印,Json 转换,...​​?

标签: java spring jpa spring-data-jpa


【解决方案1】:

双向一对多关联需要辅助方法来“链接”两个实体,请参阅manual

每当形成双向关联时,应用程序 开发人员必须确保双方始终保持同步。这 addPhone() 和 removePhone() 是同步的实用程序方法 每当添加或删除子元素时,两端都会结束。

所以你必须在Enterprise中添加至少一种这样的方法,并在将Organization添加到Enterprise时使用它:

public Enterprise addOrganization(Organization organization) {

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

我在您的代码中没有看到这种方法。我认为这是您的问题的原因。

您可以在此处找到有关一对多的其他有用信息:Best Practices for Many-To-One and One-To-Many Association Mappings

【讨论】:

  • 没有。添加或更新没有问题。我也检查了数据库。反正这个问题解决了。现在当我尝试获取记录时出现问题。在变量级别,我绘制了组织图。 @OneToMany(mappedBy = "enterprise", fetch = FetchType.EAGER) 私有列表 组织;如果我从 Enterprise.toString() 中删除组织,我就能得到它。现在的问题是,Enterprise->Organization->Enterprise->.... 递归对象构建正在发生。我只想获得一次对象。如何解决?即,只有企业->组织。
  • 所以这是另一个问题?你能把它作为新的发布吗?哪种方法帮助您解决了第一个问题(关于给出空值)?
  • @Krishna 'Enterprise->Organization->Enterprise->' - 它仅以某种方式发生。您应该发布新问题并详细说明。
【解决方案2】:

问题出在 toString() 上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2013-11-12
    • 2018-11-25
    • 2020-02-20
    • 1970-01-01
    • 2021-07-04
    • 2021-07-31
    • 2017-06-11
    相关资源
    最近更新 更多