users@glassfish.java.net

Glassfish, JPA, JTA, Hibernate & Lift - EntityManager not associated with JTA transaction

From: Kris Nuttycombe <kris.nuttycombe_at_gmail.com>
Date: Tue, 9 Sep 2008 17:28:23 -0600

Hi, all,

As you may be able to tell from the title, I'm attempting to integrate
a bunch of pieces that are almost - but not quite - meshing smoothly.
Here is my situation in a nutshell:

I have an EJB3 entity jar that I'm attempting to use in a Lift web
application running on Glassfish, using Hibernate as the persistence
provider. My JNDI data source is set up from the admin console, the
Hibernate jars have been copied into $GLASSFISH_HOME/lib, and the
web.xml of my Lift webapp includes the appropriate
<persistence-context-ref> elements to enable me to look up an
EntityManager instance from the InitialContext.

Lift runs within a servlet filter, and I am obtaining my EntityManager
by calling (new
InitialContext()).lookup("my_persistence_context_ref_name") from code
that is ultimately called by that filter. I can successfully get the
EntityManager and run a query that returns results. So far, so good.

The problem I'm running into arises when I attempt to access a
lazily-associated collection on an object returned from such a query.
I'm getting the exception:

Message: org.hibernate.LazyInitializationException: failed to lazily
initialize a collection of role:
com.gaiam.gcsi.entities.subscription.Order.subscriptions, no session
or session was closed
        org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
        org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
        org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97)
        org.hibernate.collection.PersistentBag.size(PersistentBag.java:225)

Looking at the logs, this seems unsurprising given that:

DEBUG impl.SessionImpl - opened session at timestamp: 12209986475
DEBUG ejb.AbstractEntityManagerImpl - Looking for a JTA transaction to join
DEBUG ejb.AbstractEntityManagerImpl - No JTA transaction found
DEBUG ast.QueryTranslatorImpl - parse() - HQL: FROM
com.gaiam.gcsi.entities.subscription.Order
...

My question is, at what point is a JTA transaction initiated such that
my EntityManager could join it? Is this something that I need to do
manually before I run my query? Since the persistence type of my
persistence unit is JTA, I'm unable to use
EntityManager.getTransaction() without it throwing an error. Is this
something that would ordinarily be done by the container around the
Servlet request, and the fact that Lift runs as a filter is skipping
that setup?

Many thanks,

Kris