Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jsf - h:selectOneMenu generic converter for all entities without calling DB again and again

I want to get selected object from <h:selectOneMenu>, but the problem is I couldn't find any generic converter for all type of entities.

My first question is, is there a generic converter for all type of entities? I don't want to write another converter again for each other entity. My second question is, is there a way to get selected object without any converter? I don't want to call the DB again and again.

I have a Car entity with id and name properties.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My first question is, is there a generic converter for all type of entities?

This does indeed not exist in standard JSF. The JSF utility library OmniFaces has such a converter in its assortiment, the omnifaces.SelectItemsConverter. All you need to do is to declare it as converter of an UISelectOne or UISelectMany component as follows:

<h:selectOneMenu ... converter="omnifaces.SelectItemsConverter">

See also the SelectItemsConverter showcase. This converter relies on the toString() of the object item. There's also another one, the omnifaces.SelectItemsIndexConverter, which relies instead on the index of the object item in the options list, see also the SelectItemsIndexConverter showcase.

There are currently no other JSF component/utility libraries offering the same.


Second question is, is there a way to get selected object without any converter?

No. Just use the OmniFaces one so that you don't need to create a custom converter which hits the DB. Or if you want to go overboard, create a custom renderer for <h:selectOneMenu> which renders the item index as option value and is able to set it as model value, but that's a lot of more work than a simple converter and you'd still need to do some additional work in order to get the desired object from the list based on the index — which just doesn't make any sense.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...