I’ve been using Seam for over a year. At some point the “Home” object was introduced to the documentation (Chapter 11). Reading the documentation didn’t convince me of the point. Being an ATG guy at heart, I still prefer using “form handlers” for managing my important entities. So I haven’t bothered.

However, just recently I ran into a little problem with LazyInitializationExceptions. I’m sure you’ve run into them yourself. Basically, when Hibernate loads an entity for you, it’s loaded by an entity manager which is available to manage that object within a specific scope. This effects persisting changes. Also, if you have properties on that entity that have a fetchType.LAZY, those properties can only be lazily loaded while the same entity manager is available. If it’s not, you get LazyInitializationExceptions. No fun.

So in Seam, what I usually do to avoid this, is to create a long running conversation, and load the entity within the context of that conversation. Then, as long as you’re still in that long running conversation, you can lazily load all the properties you want.

Normally this is fine. However, in my latest project the application will send e-mails to users when they get a new inter-user message. If they click on the link in the e-mail, they come to the site, but without the existing long running conversation query parameter. Their user component is session scoped, so they’re still logged in, but the user object is now outside of it’s conversation, and if you attempt to access lazily loaded properties, for instance the user’s messages they are trying to see based on the e-mail, blammo: exception central. Unhappy users.

I was pointed to this page: Using EntityHome for entities in long-running contexts

Which showed me how to use the EntityHome to avoid the whole problem. Basically it works like this:

When the user logs in, set the user entity’s id into a session scoped component. Don’t bother with long running conversations (at least not for the user). The User Home component’s Factory method creates a user component using the session scoped user id, anytime the user component is referenced. This component entity is loaded within the context of the current conversation (if it hasn’t already been loaded). So, presto-magic, no lazy loading issues.

It let me fix the issue with about 20 lines of code, and little trouble. It’s working perfectly so far.