[英]ManyToOne OneToMany bi-direction: Retrieve data from reference table
I would like to while post an object, to return the data from the reference table of the relationship.我想同时发布一个对象,以从关系的引用表中返回数据。
The relationship is defined as follow:关系定义如下:
@Entity
@Table( name = "application")
public class Application {
@Id
@JsonIgnore
private Long id;
@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;
...
}
And:和:
@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;
...
}
My product_category table has the following data:我的 product_category 表有以下数据:
While posting my Json object with the following structure:使用以下结构发布我的 Json 对象时:
...
{
"productCategory": "0"
}
...
I would like to get the following json output:我想获得以下 json 输出:
...
"productCategory": {
"productCategoryId": 0,
"description": "Personal Loan"
},
...
But instead I'm getting:但相反,我得到:
...
"productCategory": {
"productCategoryId": 0,
"description": null
},
...
Can you please advise?你能给些建议么?
There is not much code in your question, but you mentioned in your comment, what you are returning:您的问题中没有太多代码,但您在评论中提到了您返回的内容:
return applicationRepository.save(appRequest);
On the other hand, you are not cascading changes from parent to children in your mapping:另一方面,您不会在映射中将更改从父级级联到子级:
@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;
I think changing @ManyToOne
to @ManyToOne(cascade=CascadeType.ALL)
should help.我认为将@ManyToOne
更改为@ManyToOne(cascade=CascadeType.ALL)
应该会有所帮助。
Edit:编辑:
If you cannot change the model, simply return your entity:如果您无法更改模型,只需返回您的实体:
return applicationRepository.findById(id);
This way jpa won't overwrite the entity on saving, it simply reads one from db.这样 jpa 不会在保存时覆盖实体,它只是从 db 中读取一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.