Datatable不对primefaces中的元素进行排序

时间:2011-11-18 20:57:22

标签: jsf primefaces

知道为什么排序不起作用?

<h:form prependId="false">

<p:dataTable value="#{questionBackingBean.questions}"
        var="question" id="questionTable" paginator="true" rows="15"
        paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
        rowsPerPageTemplate="15,25,50" paginatorPosition="bottom">


<p:column sortBy="#{question.id}">
    <f:facet name="header">ID</f:facet>
    <h:outputText value="#{question.id}" />
</p:column>
<p:column sortBy="#{question.description}">
    <f:facet name="header">Description</f:facet>
    <h:outputText value="#{question.description}" />
</p:column>
</h:form>

提问实体

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Question)) {
            return false;
        }
        Question other = (Question) obj;
        if (id != other.id) {
            return false;
        }
        return true;
    }

支持bean

@ManagedBean
@ViewScoped
public class QuestionBackingBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private QuestionLocal questionBean;
    private List<Question> questions;
    @Inject
    private Question question;
    private int questionParamId;

    public List<Question> getQuestions() {
        questions = questionBean.findAllQuestions();

        return questions;
    }

    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }

    public Question getQuestion() {
        return question;
    }

    public void setQuestion(Question question) {
        this.question = question;
    }

    public int getQuestionParamId() {
        return questionParamId;
    }

    public void setQuestionParamId(int questionParamId) {
        this.questionParamId = questionParamId;
    }

    public void init() {
        question = questionBean.findQuestion(questionParamId);
    }

    public String addQuestion() {
        questionBean.createQuestion(question);
        return "../index.xhtml";
    }
}

2 个答案:

答案 0 :(得分:4)

每次调用getQuestions时都会返回一个新列表,在JSF中执行此操作是一种不好的做法,并且在请求生命周期中多次调用getter时会降低应用程序的速度,尤其是在数据迭代中。将问题列表缓存在属性中,getter应该只返回不加载它们的问题。

您的列表实际上是在应用请求值阶段中排序,但是在后续阶段再次调用getter时您将返回一个新实例,您在处理过程中将排序列表消失。

答案 1 :(得分:1)

你永远不应该把业务逻辑放在getter中

public List<Question> getQuestions() {
        questions = questionBean.findAllQuestions();

        return questions;
    }

将其更改为

public List<Question> getQuestions() {
        return questions;
    }

public QuestionBackingBean(){
 this.questions = questionBean.findAllQuestions();
};

当您使用@ViewScope时,每次刷新时都会调用构造函数,以便您获得最新数据。