How to properly map @OneToMany
relationship where to create entity, on @One
side of @OneToMany
relationship, it is required to have atleast one entity from @Many
side but entity on @Many
side also requires entity on @One
side to exist? To put this nightmare of a sentence simply, this is the scenario I have:
This is what I want:
[ENTITY A] 1 <-----> (1..*)[ENTITY B]
At the moment I have this:
[ENTITY A] 1 <-----> (0..*)[ENTITY B]
Which is easily done like this.
@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 my CUSTOMER
table has no column corresponding to AGREEMENT
table therefore I can't enforce rule of creating Customer
only when Agreement
is given. At the moment I can only setup rule to create Agreement
when Customer
is given because AGREEMENT
table has column corresponding to CUSTOMER
tabel, which is easily done by nullable=false
condition.
JPA doesn't provide a way to validate this, but Hibernate Validator does:
@NotNull
@Size(min=1)
public Set<Agreement> agreements = new HashSet<>();
Then you have to manually test it via the Validator:
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
validator.validate(customer)