h:selectOneMenu通用转换器,适用于所有实体,而无需一次又一次地调用DB [英] h:selectOneMenu generic converter for all entities without calling DB again and again

查看:138
本文介绍了h:selectOneMenu通用转换器,适用于所有实体,而无需一次又一次地调用DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从<h:selectOneMenu>获取选定的对象,但是问题是我找不到适用于所有类型实体的通用转换器.

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.

我有一个具有idname属性的Car实体.

I have a Car entity with id and name properties.

推荐答案

我的第一个问题是,是否存在适用于所有类型实体的通用转换器?

这在标准JSF中确实不存在. JSF实用程序库 OmniFaces 在其分类中称为c4的转换器.您需要做的就是将其声明为UISelectOneUISelectMany组件的转换器,如下所示:

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">

另请参见 SelectItemsConverter展示柜.此转换器依赖于对象项目的toString().还有另一个omnifaces.SelectItemsIndexConverter,它依赖于选项列表中对象项的索引,另请参见

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.

当前没有其他JSF组件/实用程序库提供相同的功能.

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

第二个问题是,有没有一种方法可以在没有任何转换器的情况下获取选定的对象?

不.只需使用OmniFaces即可,因此您无需创建可访问数据库的自定义转换器.或者,如果您想落水,请为<h:selectOneMenu>创建一个自定义渲染器,该渲染器将项目索引渲染为选项值,并能够将其设置为模型值,但这比简单的转换器要花很多时间,但您仍然需要做一些额外的工作,以便根据索引从列表中获取所需对象—.只是没有任何意义.

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.

  • How to populate options of h:selectOneMenu from database?
  • Conversion Error setting value for 'null Converter'
  • Implement converters for entities with Java Generics

这篇关于h:selectOneMenu通用转换器,适用于所有实体,而无需一次又一次地调用DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆