I’ve an entity LearningUnit that has an int primary key. Actually, it has nothing more.
Entity Concept has the following relationship with it:
@ManyToOne
@Size(min=1,max=7)
private LearningUnit learningUnit;
In a constructor of Concept I need to retrieve the LearningUnit with the greatest primary key. If no LearningUnit exists yet I instantiate one.
I then set this.learningUnit to the retrieved/instantied.
Finally, I call the empty constructor of Concept in a try-catch block, to have the entitymanager do the cardinality check. If an exception is thrown (I expect one in the case that already another 7 Concepts are referring to the same LearningUnit. In that case, I case instantiate a new LearningUnit with a new greater primary key.
Please, also point out, if any, clear pitfalls in my outlined algorithm above.
You can do something like this:
Actually, I wouldn’t put that logic in the constructor of your Entity (where you typically don’t have access to the entity manager, which is not a bad thing). I would implement this logic in a service method (where it belongs because I think it’s business logic).
As a side note, I think that the
@Sizeconstraint should be on the other side of the association, on theCollection.