entityManager中的nullpointerexception

时间:2014-03-07 14:33:12

标签: hibernate jpa

我正在使用Hibernate注释开发一个项目,并且我在实现EntityManager时遇到问题..在尝试EntityManager.find()时我得到了一个nullpointerexception 我不明白为什么!有什么帮助吗? 这是一些代码

    Users.java
    package com.rimweb.users.persistance;

    // Generated 6 mars 2014 12:00:34 by Hibernate Tools 3.4.0.CR1

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;

    import static javax.persistence.GenerationType.IDENTITY;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;

    /**
    * Users generated by hbm2java
    */
    @Entity
    @Table(name = "users", catalog = "user")
    public class Users implements java.io.Serializable {

private Integer userid;
private Address address;
private String username;
private String password;
private String firstname;
private String lastname;
private String email;

public Users() {
}

public Users(Address address, String username, String password,
        String firstname, String lastname, String email) {
    this.address = address;
    this.username = username;
    this.password = password;
    this.firstname = firstname;
    this.lastname = lastname;
    this.email = email;
}

@Id
@GeneratedValue(strategy =GenerationType.IDENTITY)
@Column(name = "userid", unique = true, nullable = false)
public Integer getUserid() {
    return this.userid;
}

public void setUserid(Integer userid) {
    this.userid = userid;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "addressid")
public Address getAddress() {
    return this.address;
}

public void setAddress(Address address) {
    this.address = address;
}

@Column(name = "username")
public String getUsername() {
    return this.username;
}

public void setUsername(String username) {
    this.username = username;
}

@Column(name = "password", length = 64)
public String getPassword() {
    return this.password;
}

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

@Column(name = "firstname")
public String getFirstname() {
    return this.firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

@Column(name = "lastname")
public String getLastname() {
    return this.lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

@Column(name = "email")
public String getEmail() {
    return this.email;
}

public void setEmail(String email) {
    this.email = email;
}

@Override
public String toString() {
    return "Users [userid=" + userid + ", username=" + username
            + ", password=" + password + ", firstname=" + firstname
            + ", lastname=" + lastname + ", email=" + email + "]";
}

/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((address == null) ? 0 : address.hashCode());
    result = prime * result + ((email == null) ? 0 : email.hashCode());
    result = prime * result
            + ((firstname == null) ? 0 : firstname.hashCode());
    result = prime * result
            + ((lastname == null) ? 0 : lastname.hashCode());
    result = prime * result
            + ((password == null) ? 0 : password.hashCode());
    result = prime * result + ((userid == null) ? 0 : userid.hashCode());
    result = prime * result
            + ((username == null) ? 0 : username.hashCode());
    return result;
}

/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Users other = (Users) obj;
    if (address == null) {
        if (other.address != null)
            return false;
    } else if (!address.equals(other.address))
        return false;
    if (email == null) {
        if (other.email != null)
            return false;
    } else if (!email.equals(other.email))
        return false;
    if (firstname == null) {
        if (other.firstname != null)
            return false;
    } else if (!firstname.equals(other.firstname))
        return false;
    if (lastname == null) {
        if (other.lastname != null)
            return false;
    } else if (!lastname.equals(other.lastname))
        return false;
    if (password == null) {
        if (other.password != null)
            return false;
    } else if (!password.equals(other.password))
        return false;
    if (userid == null) {
        if (other.userid != null)
            return false;
    } else if (!userid.equals(other.userid))
        return false;
    if (username == null) {
        if (other.username != null)
            return false;
    } else if (!username.equals(other.username))
        return false;
    return true;
}



}

    UsersHome.java:

    package com.rimweb.users.dao;

    // Generated 6 mars 2014 16:42:25 by Hibernate Tools 3.4.0.CR1 

    import java.util.ArrayList;
    import java.util.List;

    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import javax.persistence.PersistenceContext;
    import javax.persistence.PersistenceUnit;
    import javax.persistence.Query;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    import com.rimweb.users.persistance.Users; 

    /**
    * Home object for domain model class Users.
    * @see com.rimweb.users.dao.Users
    * @author Hibernate Tools
    */
    @Stateless
    public class UsersHome {

private static final Log log = LogFactory.getLog(UsersHome.class);

@PersistenceContext(unitName="manager1")
//@PersistenceUnit
//EntityManagerFactory entityManagerFactory=       Persistence.createEntityManagerFactory("manager1");
//private EntityManager entityManager = entityManagerFactory.createEntityManager();
private EntityManager entityManager;

public void persist(Users transientInstance) {
    log.debug("persisting Users instance");
    try {
        entityManager.persist(transientInstance);
        log.debug("persist successful");
    } catch (RuntimeException re) {
        log.error("persist failed", re);
        throw re;
    }
}

public void remove(Users persistentInstance) {
    log.debug("removing Users instance");
    try {
        entityManager.remove(persistentInstance);
        log.debug("remove successful");
    } catch (RuntimeException re) {
        log.error("remove failed", re);
        throw re;
    }
}

public Users merge(Users detachedInstance) {
    log.debug("merging Users instance");
    try {
        Users result = entityManager.merge(detachedInstance);
        log.debug("merge successful");
        return result;
    } catch (RuntimeException re) {
        log.error("merge failed", re);
        throw re;
    }
}

public Users findById(Integer id) {
    log.debug("getting Users instance with id: " + id);
    try {
        Users instance = entityManager.find(Users.class, id);
        log.debug("get successful");
        return instance;
    } catch (RuntimeException re) {
        log.error("get failed", re);
        throw re;
    }
}

public List<Users> findAll() {
    log.debug("getting all User instances");
    try {
        Query query = entityManager.createQuery("select u from Users u");
        List<Users> usersList = (List<Users>) query.getResultList();
        log.debug("findAll successful");
        return usersList;
    } catch (RuntimeException re) {
        log.error("findAll failed", re);
        return new ArrayList<Users>();
    }
  }
    }


    MainTest.java

    package com.rimweb.users.dao;
    import java.math.BigDecimal;
    import java.util.List;
    import org.hibernate.Session;
    import org.hibernate.criterion.Order;
    import com.rimweb.users.persistance.Users;

    public class MainTest {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    UsersHome dao = new UsersHome() ;

    Users us = dao.findById(new Integer(1));
    System.out.println("-Livre :"+us);

    //////////////////////////////////////////

    List<Users> list = dao.findAll(); 
    for(Users l : list)
    { System.out.println("##"+l);}


    }

}

1 个答案:

答案 0 :(得分:0)

在您的UserHome.java类中有实体管理器,但它是null,因为您正在创建刚刚定义的EntityManager。

因此,创建实体管理器,请创建Util类...

例如HibernateUtil.java

public class HibernateUtil {

    private static final EntityManagerFactory entityManagerFactory;
    static {
                try {
                     entityManagerFactory = Persistence.createEntityManagerFactory("abc");

                } catch (Throwable ex) {

                    System.err.println("Initial SessionFactory creation failed." + ex);
                    throw new ExceptionInInitializerError(ex);

                  }
    }

public static EntityManagerFactory getEntityManagerFactory() {
         return entityManagerFactory;
    }

}

并将持久性单元名称提供给以下方法而不是abc。

entityManagerFactory = Persistence.createEntityManagerFactory("abc");

然后使用事务在每个方法中创建实体管理器。

例如......

public Users merge(Users detachedInstance) {
    log.debug("merging Users instance");
    try {
        em = HibernateUtil.getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();
        Users result = entityManager.merge(detachedInstance);
        em.getTransaction().commit();
    em.close();
        log.debug("merge successful");
        return result;
    } catch (RuntimeException re) {
        em.getTransaction().rollback();
        log.error("merge failed", re);
        throw re;
    }
}

这足以避免空指针异常....