I have problems understanding how to use selection in JSF 2 with POJO/entity effectively. For example, I'm trying to select a Warehouse
entity via the below dropdown:
<h:selectOneMenu value="#{bean.selectedWarehouse}">
<f:selectItem itemLabel="Choose one .." itemValue="#{null}" />
<f:selectItems value="#{bean.availableWarehouses}" />
</h:selectOneMenu>
And the below managed bean:
@Named
@ViewScoped
public class Bean {
private Warehouse selectedWarehouse;
private List<SelectItem> availableWarehouses;
// ...
@PostConstruct
public void init() {
// ...
availableWarehouses = new ArrayList<>();
for (Warehouse warehouse : warehouseService.listAll()) {
availableWarehouses.add(new SelectItem(warehouse, warehouse.getName()));
}
}
// ...
}
Notice that I use the whole Warehouse
entity as the value of SelectItem
.
When I submit the form, this fails with the following faces message:
Conversion Error setting value 'com.example.Warehouse@cafebabe' for 'null Converter'.
I was hoping that JSF could just set the correct Warehouse
object to my managed bean when I wrap it in a SelectItem
. Wrapping my entity inside the SelectItem
was meant to skip creating a Converter
for my entity.
Do I really have to use a Converter
whenever I want to make use of entities in my <h:selectOneMenu>
? It should for JSF be possible to just extract the selected item from the list of available items. If I really have to use a converter, what is the practical way of doing it? So far I came up to this:
- Create a
Converter
implementation for the entity. - Overriding the
getAsString()
. I think I don't need this since the label property of theSelectItem
will be used to display the dropdown option label. - Overriding the
getAsObject()
. I think this will be used to return the correctSelectItem
or entity depending on the type of the selected field defined in the managed bean.
The getAsObject()
confuses me. What is the efficient way to do this? Having the string value, how do I get the associated entity object? Should I query the entity object from the service object based on the string value and return the entity? Or perhaps somehow I can access the list of the entities that form the selection items, loop them to find the correct entity, and return the entity?
What is the normal approach of this?