views:

35

answers:

1

I'm getting an NPE for my EntityManager and can't figure out why - can anyone spot my mistake?

UserManagerImpl.java

@Stateless
public class UserManagerImpl implements UserManager {

 @PersistenceContext(unitName = "persistenceUnit")
 EntityManager em;

 public List<User> findUsers() {
  return (List<User>) em.createQuery("from User").getResultList();
 }
}

META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
 <persistence-unit name="persistenceUnit">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <jta-data-source>java:/DefaultDS</jta-data-source>
  <properties>
   <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
   <property name="hibernate.hbm2ddl.auto" value="create" />
  </properties>
 </persistence-unit>
</persistence>

These are inside my ejb jar project, the UserManagerImpl is invoked from a JSP, not sure that should make a difference though.

Thanks in advance.

+1  A: 

When you are using new UserManagerImpl() the container has no way to inject the EntityManager into this class. You need to let the container inject an instance into your object using

@EJB
private UserManager userManager;

This will only work for container managed objects like JSF managed beans, servlets or JSPs. Alternatively you can look up the ejb from jndi using something like

new InitialContext().lookup("UserManagerImpl");

The actual jndi name might be different.

Jörn Horstmann