1

I'm trying to write a converter class that will convert between an Employee object and a String (for display purposes). The end goal is to have a SelectOne field on a form which displays a list of all the employee numbers in the database.

Here's what I have so far:

@FacesConverter(value = "employeeConverter")
public class EmployeeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        Employee tmp = Helper.findEmployee(em, value);
        return tmp;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        Employee tmp = (Employee) value;
        return tmp.getEMPLOYEE_NUMBER();
    }
}

So, the issue I'm running into is that the Helper class (which basically runs SQL queries for me - I can include it if needed) requires that I pass it an EntityManager. As I've figured out through searching, I can't just include the EntityManager in this class because it's outside of the "scope" of the web stuff.

I'm new to using Java for the web, and very new to using databases with Java. Can someone explain how I can use a converter this way to query my database and have a Select box with employee numbers in it.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
n0pe
  • 9,209
  • 21
  • 81
  • 146

1 Answers1

1

Since the converter Methods are containing a reference to the FacesContext, you can always use that one to evaluate an EL-Expression that will return your Service in Question.

If you are not using any dedicated DataServices, you could use a "Helper bean", which does nothing but contain a reference to an EntityManager:

@Named
public class RandomHelperBean{

   @PersistenceContext(unitName = "yourPersistenceContext") 
   EntityManager em;

   public EntityManager getEm(){
      return em;
   }
}

and from within your converter:

public Object getAsObject(FacesContext context, UIComponent component, String value) {

    RandomHelperBean rhb= context.getCurrentInstance().getApplication().evaluateExpressionGet(context, "#{randomHelperBean}", RandomHelperBean.class);
    EntityManager em = rhb.getEm();
    Employee tmp = Helper.findEmployee(em, value);
    return tmp;
}

Pretty much untested, but it should be something like this.

dognose
  • 18,985
  • 9
  • 54
  • 99
  • This looks like something that would work. I'll giver her a go and let you know. Thanks! – n0pe Oct 12 '14 at 19:18