0

大家好,我对 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> 

我错过了什么?我不明白为什么要获得空指针。

4

1 回答 1

2

确保在您的 WAR 项目中有一个persistence.xml文件。此外,不可能同时使用@ManagedBean@FacesConverter。您需要删除@FacesConverter<converter>避免混淆,并将转换器专门用作托管 bean,如下所示:

<h:inputText converter="#{convertToCustomer} />

此外,你为什么不@PersistenceContext直接注入:

@PersistenceContext
EntityManager em;
于 2013-04-11T13:27:24.083 回答