This question sort of asks what I'm trying to achieve, but there isn't really an answer : Hibernate validateManyToOne
has at least one
I have two objects (A and B). A is the parent. B is the child. It's a one to many relationship, however, I need there to always be at least one B for each A. There are default values for all fields in B, so if an A is created without a B then a default B can be added to make sure there is always one B. If one or more B objects are added A then there's no need to create a default B.
This is A:
[Fields]
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "key", nullable = false)
@Fetch(value = FetchMode.SUBSELECT)
private List<B> b = new ArrayList<>();
...
@PrePersist
protected void onCreate() {
// Default values configured here, for example
if (fieldA1 == null) {
fieldA1 = "A DEFAULT";
}
...
}
This is B:
[Fields]
@PrePersist
protected void onCreate() {
// Default values configured here, for example
if (fieldB1 == null) {
fieldB1 = "B DEFAULT";
}
...
}
I thought I could use the same @PrePersist annotation in A, check if there are any B objects, and if not create a default B:
@PrePersist
protected void onCreate() {
// Deafult values configured here
...
if (b.size() == 0) {
b.add(new B());
}
}
That doesn't work. If I create an A with no B objects then in the log I just get:
Handling transient entity in delete processing
and A is created without the B. If I try and create an A with at least one B then I get the following error:
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
Any ideas how I can make this work?