考虑以下课程:
package com.deluxe.common.dao;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.faces.bean.ManagedBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.deluxe.jpa.Customer;
@ManagedBean(name="jpaBean")
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class JpaDao {
@PersistenceContext(unitName="EmployeeService")
EntityManager em;
public EntityManager getEntityManager() {
return em;
}
public void addEmployee(String name, String lastName) {
Customer cust = new Customer();
cust.setName(name);
cust.setLastName(lastName);
em.persist(cust);
}
}
当我通过JSF托管bean调用addEmployee时,entitymanager为null但是当我在jsf bean中打印entitymanager时它会显示出来。这是jsf托管bean的代码:
@EJB JpaDao psb;
public void addCustomer() {
EntityManager em = psb.getEntityManager();
JpaDao jpa = new JpaDao();
jpa.addEmployee("Some..", "Thing.."); // Throwing err, em in JpaDao is null.
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+em); //This line show em is there.
Customer cust = new Customer();
cust.setLastName("Krishnawat");
cust.setName("Nagendra");
em.persist(cust);
}
为什么会这样?我错过了什么。
答案 0 :(得分:-1)
我看到你没有声明你的实体经理和你的ejb JpaDao,我认为这是一个坏习惯。我想你可以开始尝试私有你的entityManager,把相应的getter和setter放在尊重约定的地方,然后再试一次。因为我对另一个属性有一些问题而且是因为这样的事情