How to find the entity with the greatest primary key?
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.
How to find the entity with the greatest primary key?
You can do something like this:
try {
Query q = entityManager.createQuery("from LearningUnit unit order by unit.id desc");
q.setMaxResults(1);
LearningUnit unit = (LearningUnit) q.getSingleResult();
// we found a LearningUnit
// ...
} catch (NoResultException e) {
// We didn't find any LearningUnit
// ...
}
Please, also point out, if any, clear pitfalls in my outlined algorithm above.
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 @Size
constraint should be on the other side of the association, on the Collection
.
精彩评论