JPA @OneToMany and 1 – 1..* relationship
How to properly map @OneToMany
the relationship @OneToMany
the side of the entity created on the @One
, requires at least one side of the entity from the @Many, but the entity needs to @One
on the @Many
side
Does the solid edge exist? Simply put, this nightmare is the scene I encountered:
That’s what I want:
[ENTITY A] 1 <-----> (1..*)[ENTITY B].
Currently I have this :
[ENTITY A] 1 <-----> (0..*)[ENTITY B].
It’s easy to do.
@OneToMany(cascade=CascadeType.ALL, mappedBy="customer")
public Set<Agreement> agreements = new HashSet<>();
and
@ManyToOne
@JoinColumn(name = "CUSTOMER_ID", nullable=false)
private Customer customer;
So the problem is that I don’t have a list of AGREEMENTS
in my CUSTOMER
table, so I can’t enforce the rule for creating a Customer
only if the Agreement
is given. Currently I can only set rules to create an agreement
when Customer
is given because the AGREEMENT
table has a column tabel corresponding to CUSTOMER
, which is easy to accomplish by nullable=false
condition.
Solution
A lot depends on the type of relationship you want to strengthen. If the protocol can exist independently of the customer, then this means that the customer_id in the protocol must be nullable.
If the protocol cannot exist on its own, it is assumed that the customer ID is not nullable, in which case the protocol cannot be created first without creating the customer. This means that you have a stronger connection between the customer and the corresponding protocol.
Once we are sure that we have a strong relationship, we need to investigate how strong it really is and who will have whom. Usually, it is the multiple parties that own the relationship, and updates happen through the multiple parties. This means that your JoinColumn needs to be on MANY and the mapper needs to be on ONE.
This is an interesting case where ownership is reversed when one party actually owns the relationship, in which case the foreign key of the multiple party cannot be NULL because the owning party has no way of knowing what the multi-party key is.