I have a quite simple Data model with a unidirectional one-to-one mapping between the parent-entity Foo and the child-entity Bar
The parent has the mapping defined as following:
@Valid
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "bar_id")
private Bar bar;
inside the Bar class I have lists of other objects which I expect to have at least one Element so I added @NotEmpty to them
@NotEmpty
private List<Other> other = new ArrayList<>();
When I create a new Foo object and set the bar reference with both entities not persisted the validation works as expected. However if the Foo Object already exists and I just add a new Bar reference to it validation fails. I debugged it and found out the ArrayList with lenght > 0 gets swapped by a Hibernate PersistentList (so far so good) with a length of 0 (not what I expect). If I persist Bar beforehand it works again.
Basic pseudo-test-case:
@Transactional
void works() {
var foo = new Foo();
var bar = new Bar();
var other = otherRepository.findById(1L);
bar.addOther(other);
fooRepository.save(foo);
// checks if bar.other has correct length
}
@Transactional
void doesntWork() {
var foo = fooRepository.findById(1L);
var bar = new Bar();
var other = em.find(Other.class, 1L);
bar.addOther(other);
fooRepository.save(foo);
// breaks with constraint violation because bar.child cannot be empty
}
I'm curious if I just misunderstand how cascade is supposed to work or if I found a bug in Hibernate. Versions are Hibernate-core 5.6.14.FINAL and hibernate Validator 6.2.5.Final
If it happens to be a Bug I could work around it by persisting first but I'd prefer a clean approach that 2-years-from-now-Me doesnt have to worry about
thanks in advance for reading this far! hope you have a beautiful day.