如何正确呈现JSF中存储在数据库中的类别列表 [英] How to present a list of categories stored in database in JSF correctly

查看:172
本文介绍了如何正确呈现JSF中存储在数据库中的类别列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在申请我要注册的问题。每个问题都与一个或多个类别有关系,所以我需要在注册问题表单中选择一个方法来选择它所属的类别。

I am making an application where I am going to register questions. Each question has a relationship with one or more categories so I need a way in the register question form to select which categories it belongs to.

我正在考虑使用其中一个类别来自JSF的selectMany ...组件用于任务。我可以检索数据库中所有类别的列表(仅9个),然后将该列表绑定到f:selectItems组件。然后每个selectItem的itemValue必须是类别的id。我还需要第二个列表,其中包含所有选定的类别ID,最后再使用每个id对数据库进行某种查询,并将其添加到列表....再次在问题上设置。

I am thinking of using one of the selectMany... components from JSF for the task. I could retrieve the list of all categories in the database (only 9) and then bind that list to a f:selectItems component. Then the itemValue of each selectItem must be the id of the category. I will also need a second list containing all the selected id's of the categories and at last do some sort of query against the database again with each id and add it to the list ....which again is set on the question.

我不需要解释如何检索列表等但如果这种方法有任何好处我可能需要一些帮助吗?备选方案被广泛接受:=)

I do not need a explanation on how to retrieve the list etc. but I could need some help if this approach is any good? Alternatives is well accepted:=)

推荐答案

制作列表<类别> 问题实体的属性。

@Entity
public class Question {

    @OneToMany
    private List<Category> categories;

    // ...
}

<h:selectManyMenu value="#{question.categories}" converter="#{categoryConverter}">
    <f:selectItems value="#{data.categories}" />
</h:selectManyMenu>

您只需为类别 class。

You only need to supply a converter for Category class.

@ManagedBean
@RequestScoped
public class CategoryConverter implements Converter {

    @EJB
    private CategoryService categoryService;

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Category) || ((Category) value).getId() == null) {
            return null;
        }

        return String.valueOf(((Category) value).getId());
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || !value.matches("\\d+")) {
            return null;
        }

        return categoryService.find(Long.valueOf(value));
    }

}

(注意:它是直到JSF 2.2无法在 @FacesConverter 中注入 @EJB ,这就是为什么它是 @ManagedBean 相反,另请参阅 JSF 2.0中的通信 - 转换和验证GET请求参数

(note: it's until JSF 2.2 not possible to inject an @EJB in a @FacesConverter, that's why it's a @ManagedBean instead, see also Communication in JSF 2.0 - Converting and validating GET request parameters)

您不需要复制托管bean中的选定项目或者别的什么。

You don't need to duplicate the selected items in the managed bean or something else.

这篇关于如何正确呈现JSF中存储在数据库中的类别列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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