0

I have a JpaController class like this:

public class JpaController
{
  @Inject private EntityManager em;

  @Transactional
  public void create(Message msg)
  {
    em.persist(msg);
  }
}

and I'm installing a com.google.inject.persist.PersistFilter (although not filtering through it because I'm not in an HTTP request at this point, it's a background thread).

I also install a new JpaPersistModule(PU)

The EntityManager is successfully populated I think (though I wouldn't be confident of this because the code doesn't reach that line).

The exception that gets thrown is from the interceptor for @Transactional

java.lang.NullPointerException
  at org.eclipse.persistence.internal.jpa.EntityManagerImpl.getActivePersistenceContext(EntityManagerImpl.java:1712)
  at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.begin(EntityTransactionImpl.java:49)
  at com.google.inject.persist.jpa.JpaLocalTxnInterceptor.invoke(JpaLocalTxnInterceptor.java:62)
  at my code - the line that called controller.create(msg);

Libraries used: EclipseLink 2.4.1, guice 3.0, guice-persist 3.0, guice-jndi 3.0, guice-servlet 3.0, MySQL 5.1.25, javax.persistence 2.0.4, Jackson, activemq, lombok, joda-time, javax.mail, javax.inject, asm, jersey, log4j, jettison, jsr311.

mjaggard
  • 2,090
  • 1
  • 20
  • 36
  • 1
    I believe this error can only occur if the EM is closed after the getTransaction() call, since starting the transaction requires the EntityManager remain open, but I am not familiar with the setup to tell you why the EM would have been closed. Perhaps provide the configuration and someone might be able to see what is going wrong. – Chris Sep 10 '13 at 15:19

2 Answers2

1

There are quite issues injecting directly an EntityManager, that could be closed, without connections,...

Instead of injecting an EntityManager, try to implement ths it through a guice provider :

public class JpaController
{
  @Inject private Provider<EntityManager> _entityManagerProvider;

  @Transactional
  public void create(Message msg)
  {
    _entityManagerProvider.get().persist(msg);
  }
}

Teorically, emProvider.get() will always return a valid EntityManager instance througth JpaPersistModule

Community
  • 1
  • 1
Azimuts
  • 1,102
  • 3
  • 14
  • 33
0

My guess is that your persistence unit failed to start/initialize, or is not configured correctly.

Enable logging on finest (in your persistence.xml) to see if any errors occurred on deployment. Also try using a debugger to see what is null.

James
  • 19,367
  • 9
  • 72
  • 129