views:

16

answers:

1

I have a database with 2 tables CD and Song. Session bean access then entity classes of those two tables. In my backing bean, I just have a String cd and HashMap<CDName, CDName> cds that will hold the list of CD return back from my sessionbean, so in JSF I would do something like this.

<h:selectOneMenu id="cd" value="#{backingBean.cd}">
     <f:selectItem itemLabel="Select CD" itemValue="" />
     <f:selectItems value="#{backingBean.cds}" />
</h:selectOneMenu>

This successfully load a list of cd onto the drop down list, and if I select a cd, cd variables would hold the name of the CD I select. This work great if CDName is unique. But unfortunately it is not. So what I want is HashMap<ID, CDName> cds where ID is the PK in table CD. But now how I can set it up, so when I click on a item from the CD drop down list, I get the ID back in my backingbean, so that I can do something like this, in my session bean

CD cd = EntityManager.find(CD.class, the id that I get back from JSF page)

essentially I want to obtain the cd object that I just click on, keep it in mind, there might be duplication. If my design is bad, please point out. Help please. Thanks in advance

+2  A: 

It will be set in the property behind #{backingBean.cd} as illustrated in your code example.

So, basically:

CD cd = em.find(CD.class, this.cd);

Alternatively, you can also have a HashMap<CD, CDName> instead and use a javax.faces.convert.Converter which does basically the following:

public Object getAsObject(FacesContext context, UIComponent component, String value) {
    return em.find(CD.class, value);
}

public String getAsString(FacesContext context, UIComponent component, Object value) {
    return String.valueOf(((CD) value).getId());
}

See also:


That said, a HashMap is by nature unordered. Are you sure you don't rather need a TreeMap (automatic sort by key) or a LinkedHashMap (insertion order)?

BalusC
In your `Backing Map`, can u just not return `Map<String, Object>` directly to the JSF, or do you have to convert it into `List<SelectItem>` like what you did?
Harry Pham
Not directly, the key-value pair should be swapped to get it displayed as you want. I.e. `Map<Object, String>`. The `Map` key will namely become option value and the `Map` value will become the option label.
BalusC
Make perfect sense. Thanks a lot balusC
Harry Pham
You're welcome.
BalusC
shouldn't `EntityManager` be lower-case? :)
Bozho
Yes, it should be a variable :)
BalusC