I have a Parent entity with a Child entity in a ManyToOne relationship:
@Entity class Parent {
// ...
@ManyToOne((cascade = {CascadeType.ALL})
private Child child;
// ...
}
The Child has an unique field:
@Entity class Child {
// ...
@Column(unique = true)
private String name;
// ...
}
When I need a new Child, I ask the ChildDAO first:
Child child = childDao.findByName(name);
if(child == null) {
child = new Child(name);
}
Parent parent = new Parent();
parent.setChild(child);
The problem is, if I do like above twice (with the same name for the Child), and only persist the Parent at the end, I get a constraint exception. Which seems normal, since initially there was no child in the database with the specified name.
The problem is, I'm not sure what would be the best way to avoid this situation.