NullPointerException with JPA, Eclipselink and Guice

1.3k views Asked by At

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.

2

There are 2 answers

0
James On

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.

0
Azimuts On

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