【问题标题】:ManyToOne OneToMany bi-direction: Retrieve data from reference tableManyToOne OneToMany 双向:从参考表中检索数据
【发布时间】:2019-07-16 15:10:04
【问题描述】:

我想同时发布一个对象,从关系的引用表中返回数据。

关系定义如下:

@Entity
@Table( name = "application")
public class Application {

    @Id
    @JsonIgnore
    private Long id;

    @ManyToOne
    @JoinColumn(name = "product_category")
    private ProductCategory productCategory;

    ...

}

还有:

@Entity
@Table(name = "product_category")
public class ProductCategory {

    @Id
    @Column(name = "product_category_id")
    private Long productCategoryId;

    @Column(name = "description")
    private String description;

    @JsonIgnore
    @OneToMany(mappedBy = "productCategory")
    private Set<Application> applications;

    ...
}

我的 product_category 表有以下数据:

在使用以下结构发布我的 Json 对象时:

...
{
  "productCategory": "0"
}
...

我想得到以下 json 输出:

...
"productCategory": {
    "productCategoryId": 0,
    "description": "Personal Loan"
},
...

但我得到的是:

...
"productCategory": {
    "productCategoryId": 0,
    "description": null
},
...

你能建议吗?

【问题讨论】:

  • 你能贴出生成 json 响应的代码吗?
  • 这只是一个简单的repository返回。 return applicationRepository.save(appRequest);
  • 没有看到你的代码就无话可说

标签: java spring spring-boot hibernate hibernate-mapping


【解决方案1】:

您的问题中没有太多代码,但是您在评论中提到了您要返回的内容:

return applicationRepository.save(appRequest);

另一方面,您不会在映射中将父级更改级联到子级:

@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;

我认为将 @ManyToOne 更改为 @ManyToOne(cascade=CascadeType.ALL) 应该会有所帮助。

编辑:

如果您无法更改模型,只需返回您的实体:

return applicationRepository.findById(id);

这样 jpa 不会在保存时覆盖实体,它只是从 db 中读取一个。

【讨论】:

  • product_category 表中已经存在数据。如果我错了,请纠正我,但如果我不想将更改传播到引用表,我不需要使用该选项。
  • save 来自CrudRepository 的方法返回持久/合并的实体。也许db中的数据视图没有刷新。你试过我的建议了吗?
  • 在这种情况下我不能使用它。 product_category 具有此 json 对象未提供的必需描述字段...所以我不能仅发布 id,因为它返回空描述字段的错误
  • return applicationRepository.findById(id)怎么样?
  • 如果我搜索一个实体就可以了!你知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2015-06-06
相关资源
最近更新 更多