You can find the full source code for this website in the Seam package in the directory /examples/wiki. It is licensed under the LGPL.
| Online: | 8 Members of 3259 |
Seam solves the problem of LazyInitializationExceptions (LIE) for Conversations using a Seam Managed Persistence Context (SMPC). Seam's EntityHomes make it trivial to solve this problem for longer scopes - SESSION, APPLICATION and BUSINESS_PROCESS.
@Name("currentUserHome")
public class CurentUserHome extends EntityHome<User> {
@Out(scope=ScopeType.SESSION, required=false)
@In(required=false)
private Integer currentUserId;
@Factory(value="currentUser")
public User getCurrentUser() {
return getInstance();
}
@Override
protected User createInstance() {
if (currentUserId != null) {
return getEntityManager().find(User.class, currentUserId);
} else {
return new User();
}
}
}
Then, to set the current user
, just outject currentUserId into SESSION scope.
Well, if you simply annotate your entity with @Name and @Scope, then, when loaded (using a SMPC) and outjected, it is stored in the desired context. BUT, if you then leave the conversation in which it was loaded, you will get an LIE if you access a property which was not initialised inside that conversation. Ouch.
So, instead of storing the entity in a scope longer than Conversation, we store the id of the entity in the long running scope and the entity in the conversation. Using a @Factory we initialise the entity context variable. If the id is null a new entity is created, otherwise a fresh copy of the entity is loaded and attached to this conversation.
I really like this approach better than an example I had provided and I think I'll use it :) It's really nice not to have to carry the currentUser (and potentially its associations) in memory unless absolutely needed by the current context. Thanks Pete.
You can also use the hibernate cache so your objects are always attached in a conversation and no database calls are made!
This is really helpful! Thank you.
@Tom: can you elaborate or provide a link? Thanks!
--
Devon Hillard
Tech Blog