简体   繁体   中英

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:

在此处输入图片说明

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?

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.

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