0

Hi guys I have a problem with jsf managed bean and @PersistenceUnit. I'm using this converter

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;
    }

}

and I got null pointer exception on EntityManagerFactory. In my faces-config file I have:

<converter>
<converter-id>convertToCustomer</converter-id>
<converter-class>crasmonclient.converter.ConvertToCustomer</converter-class>
</converter> 

Did I miss something? I don't understand why getting null pointer.

Odgiiv
  • 683
  • 1
  • 11
  • 32
  • Related: http://stackoverflow.com/questions/7572335/how-to-use-ejb-inject-and-or-autowired-in-facesvalidator/7572413#7572413 – BalusC Apr 11 '13 at 14:00

1 Answers1

2

Make sure in your WAR project, there is a persistence.xml file. Furthermore, it's not possible to use @ManagedBean and @FacesConverter at the same time. You need to remove @FacesConverter and <converter> to avoid confusion and use the converter exclusively as managed bean as follows:

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

Besides, why don't you inject the @PersistenceContext directly:

@PersistenceContext
EntityManager em;
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Mr.J4mes
  • 9,168
  • 9
  • 48
  • 90