大家好我有jsf托管bean和@PersistenceUnit的问题。我正在使用这个转换器
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import mn.bsoft.crasmonclient.model.Customer;
/**
*
* @author D
*/
@ManagedBean
@RequestScoped
@FacesConverter(value="convertToConverter")
public class ConvertToCustomer implements Converter{
@PersistenceUnit(unitName = "CrasmonClientPU")
private EntityManagerFactory entityManagerFactory;
private EntityManager em;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
em = entityManagerFactory.createEntityManager();
Object ret = em.find(Customer.class, new Integer(value));
return ret;
} catch (ConverterException e) {
System.out.println(e.getFacesMessage());
}
return null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
try {
Customer pa = (Customer) value;
return String.valueOf(pa.getCustomerId());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
我在EntityManagerFactory上得到了空指针异常。在我的faces-config文件中,我有:
<converter>
<converter-id>convertToCustomer</converter-id>
<converter-class>crasmonclient.converter.ConvertToCustomer</converter-class>
</converter>
我错过了什么吗?我不明白为什么得到空指针。
答案 0 :(得分:2)
确保在WAR项目中有一个persistence.xml
文件。此外,无法同时使用@ManagedBean
和@FacesConverter
。您需要删除@FacesConverter
和<converter>
以避免混淆,并将转换器专门用作托管bean,如下所示:
<h:inputText converter="#{convertToCustomer} />
此外,为什么不直接注射@PersistenceContext
:
@PersistenceContext
EntityManager em;