尝试在DB中查找实体时,EntityManager为null

时间:2014-11-11 21:38:46

标签: hibernate java-ee

我正在尝试学习Java EE编程,但我坚持使用hibernate配置。 尝试调用getEntityManager().find(entityClass, id);时,我收到NullPointerException,因为实体管理器为空。你能帮忙吗?

配置:

  • netbeans的
  • jsf 2.2
  • primefaces
  • hibernate 4.3.1

WEB-INF / web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/login.xhtml</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
</web-app>

WEB-INF /应用context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- DAO declarations -->
    <bean id="userDao" class="com.example.j2eeapp.dao.UserJpaDao" />
    <context:annotation-config />

</beans>

META-INF / persistence.xml中

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="com.logintest_JeeHibernate_war_1.0-SNAPSHOTPU" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>MySqlTestUser</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

netbeans生成的UsersFacade.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logintest.jeehibernate.entity;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

/**
 *
 * @author skoczo
 */
@Transactional
public class UsersFacade extends AbstractFacade<Users> {
    @PersistenceContext(unitName = "com.logintest_JeeHibernate_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UsersFacade() {
        super(Users.class);
    }

    protected void setEntityManager(EntityManager em) {
        this.em = em;
    }
}

netbeans生成的AbstractFacade.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logintest.jeehibernate.entity;

import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author skoczo
 */
public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

LoginBean我的代码,用于检查用户是否存在于DB

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logintest.logintest.login;

import com.logintest.jeehibernate.entity.Users;
import com.logintest.jeehibernate.entity.UsersFacade;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author skoczo
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private String password;
    private String message, uname;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String loginProject() {

        if (exist()) {
            return "logged";
        } else {
//            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Login!", "Please Try Again!"));
//            FacesContext.getCurrentInstance().addMessage(
//                    "messages",
//                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
//                            "Invalid Login!",
//                            "Please Try Again!"));
            FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Wrong username or password!!!", null);
            FacesContext.getCurrentInstance().addMessage(null, facesMessage);
            // invalidate session, and redirect to other pages
            //message = "Invalid Login. Please Try Again!";
            return "";
        }

    }

    public String logout() {

        return "login";
    }

    private boolean exist() {
        Users find = (new UsersFacade()).find(uname);
        if (find.getPassword().equals(password)) {
            return true;
        }
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

您的UsersFacade不是由容器管理的 - 它不是托管bean,因此不会执行依赖注入。您可以将托管bean或(建议的解决方案)注入EntityManager LoginBean UserFacade,并通过构造函数将其传递到您的外观。