简体   繁体   English

未注入EntityManager

[英]EntityManager not injected

I'm getting an NPE for my EntityManager and can't figure out why - can anyone spot my mistake? 我正在为我的EntityManager获取NPE,却不知道为什么-有人可以发现我的错误吗?

UserManagerImpl.java 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 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. 这些都在我的ejb jar项目中,从JSP调用UserManagerImpl,但不确定是否有所作为。

Thanks in advance. 提前致谢。

When you are using new UserManagerImpl() the container has no way to inject the EntityManager into this class. 当使用new UserManagerImpl() ,容器无法将EntityManager注入此类。 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. 这仅适用于容器管理的对象,例如JSF管理的Bean,Servlet或JSP。 Alternatively you can look up the ejb from jndi using something like 另外,您可以使用类似的方法从jndi查找ejb

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

The actual jndi name might be different. 实际的jndi名称可能不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM