Issue
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:
While posting my Json object with the following structure:
...
{
"productCategory": "0"
}
...
I would like to get the following json output:
...
"productCategory": {
"productCategoryId": 0,
"description": "Personal Loan"
},
...
But instead I'm getting:
...
"productCategory": {
"productCategoryId": 0,
"description": null
},
...
Can you please advise?
Solution
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.
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.
Answered By - Andronicus