Friday, May 21, 2010

Revised Seam Application Scoped Repositories

In yesterdays blog I wrote about repositories in a Seam application that have application scope. In this blog I also presented a possible solution. In this blog I wish to present a better solution that also makes use of the Seam Managed Persistence Contexts.


Seam has a way to manage your persistence context (Hibernate Session) for you, so that you don't need to care about the dreaded LazyInitializationException. Seam does this via the Seam Managed Persistence Context. This is a built in Seam component that maintains a (Hibernate) Session for you in the Conversation context. However as our Repositories are Application context scoped, they are a singleton and thus we cannot inject the Session in them.

In our approach from yesterday, we broke this feature, because we obtained our own session from the SessionFactory (which was injected by Seam), and closing that session. Luckily Seam has a way to programmatically obtain any component. Let's have a look at a new solution to this problem:


@Name("petRepository")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class HibernatePetRepository implements PetRepository {

public List<Pet> loadSomePets() {
Session session = (Session) Component.getInstance("hibernateSession");
return session.createQuery("from Pet").list();
}

... omitted methods ...
}


In this way, we obtain the Session for the specific Conversation or request of the user.

No comments:

Post a Comment