views:

32

answers:

1

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.

+1  A: 

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.

Pascal Thivent
Isn't that boilerplate code? I was wondering if something like EntityManager.findMax(LearningUnit, id) existed.
simpatico
@simpatico: To my knowledge, there is nothing built-in for that (you usually don't deal with ids with JPA).
Pascal Thivent
also, aren't you missing a "SELECT"?
simpatico
@simpatico: No, I'm not. Try it yourself.
Pascal Thivent
"you usually don't deal with ids with JPA"I wonder if I should discuss my db design, then. I need this learningunit to impose a grouping constraint. Concepts are 'published' to a memo (entity) in 4 groups (learningunits). I deal with the max id to first-come first-publish. I may still re-schedule a Concept by assigning it to a greater lunit.
simpatico
Put another way, how would you alter my algo/schema to achieve with jpa code that is usual, not dealing with ids?
simpatico