0

I have two entities: person and car. One person can have multiple cars. This should be a bidirectional relationship.

I'm wondering which entity should be the owner of relationship?

I made it like this, but somebody told me, he would do it in the opposite direction, because the goal is to ask person for information and a car is one of the information, which a person gives.

I found some information for manytomany relationship JPA: which side should be the owning side in a m:n relationship? but no for 1:n.

Person entity:

@JsonIgnore
@OneToMany(mappedBy = "person")
private Set<Car> cars = new HashSet<Car>();

Car entity:

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "person_car", joinColumns = @JoinColumn(name = "car_id"),
           inverseJoinColumns = @JoinColumn(name = "person_id"))
private Person person;
Zk_1990
  • 47
  • 5
  • 2
    The child, which holds the FK to the parent, owns the relationship. This is shown by `mappedBy = "person"` Look up the javadoc for mappedBy. `because the goal is to ask person for information and a car is one of the information, which a person gives` is meaningless in this context. The `owner` of the relationship is the entity responsible for persisting relations. You fill out the parent field in the child before when persisting children relations and the child entity stores the parent FK in its table. Also, remove this nonsense `(cascade = CascadeType.ALL, fetch = FetchType.EAGER)` . – K.Nicholas Jan 31 '22 at 14:40
  • Hi, thank you very much for your help. So I removed (cascade = CascadeType.ALL, fetch = FetchType.EAGER) but now I get: "nvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing". – Zk_1990 Jan 31 '22 at 15:14
  • So I found out, I should add CascadeType.ALL to the parent? – Zk_1990 Jan 31 '22 at 15:15
  • 2
    Sounds like a different question, but did you save the Parent first? EDIT: And, no, you should not add `CascadeType` to anything without a specific reason and "because it works for the bad code I wrote" is not a specific reason. – K.Nicholas Jan 31 '22 at 15:15
  • No, I didn't save parent :( – Zk_1990 Jan 31 '22 at 15:20
  • 1
    Need to save that first so it has a PK to use as child's FK. – K.Nicholas Jan 31 '22 at 15:21
  • 1
    Ok I understand, thank you very much! :) – Zk_1990 Jan 31 '22 at 15:29

0 Answers0