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
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());
}
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)?