title: Generic JSF entity converter
body: <p>I'm writing my first Java EE 6 web app as a learning exercise.  I'm not using a framework, just JPA 2.0, EJB 3.1 and JSF 2.0. </p>
  
  <p>I have a Custom Converter to convert a JPA Entity stored in a SelectOne component back to an Entity. I'm using an InitialContext.lookup to obtain a reference to a Session Bean to find the relevant Entity. </p>
  
  <p>I'd like to create a generic Entity Converter so I don't have to create a converter per Entity. I thought I'd create an Abstract Entity and have all Entities extend it.  Then create a Custom Converter for the Abstract Entity and use it as the converter for all Entities. </p>
  
  <p>Does that sound sensible and/or practicable?  </p>
  
  <p>Would it make more sense not to have an abstract entity, just a converter that converts any entity?  In that case I'm not sure how I'd obtain a reference to the appropriate Session Bean.</p>
  
  <p>I've included my current converter because I'm not sure I'm obtaining a reference to my Session Bean in the most efficient manner.</p>
  
  <pre><code>package com.mycom.rentalstore.converters;
  
  import com.mycom.rentalstore.ejbs.ClassificationEJB;
  import com.mycom.rentalstore.entities.Classification;
  import javax.faces.application.FacesMessage;
  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.naming.InitialContext;
  import javax.naming.NamingException;
  
  @FacesConverter(forClass = Classification.class)
  public class ClassificationConverter implements Converter {
  
      private InitialContext ic;
      private ClassificationEJB classificationEJB;
  
      @Override
      public Object getAsObject(FacesContext context, UIComponent component, String value) {
  
          try {
              ic = new InitialContext();
              classificationEJB = (ClassificationEJB) ic.lookup("java:global/com.mycom.rentalstore_RentalStore_war_1.0-SNAPSHOT/ClassificationEJB");
  
          } catch (NamingException e) {
              throw new ConverterException(new FacesMessage(String.format("Cannot obtain InitialContext - %s", e)), e);
          }
  
          try {
              return classificationEJB.getClassificationById(Long.valueOf(value));
          } catch (Exception e) {
              throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Classification - %s", value, e)), e);
          }
      }
  
      @Override
      public String getAsString(FacesContext context, UIComponent component, Object value) {
          return String.valueOf(((Classification) value).getId());
      }
  }
  </code></pre>