Reputation: 49107
Any idea why the sorting does not work?
<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>
Question entity
@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;
}
Backing 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";
}
}
Upvotes: 2
Views: 5667
Reputation: 17471
You should never put business logic in getter
public List<Question> getQuestions() {
questions = questionBean.findAllQuestions();
return questions;
}
change it to
public List<Question> getQuestions() {
return questions;
}
and
public QuestionBackingBean(){
this.questions = questionBean.findAllQuestions();
};
As you are using @ViewScope the constructor will get called every time you refresh so you have latest data.
Upvotes: 1
Reputation: 6504
You are returning a new list everytime getQuestions is called, doing this in JSF is a bad practice and slows down your app as getters are called multiple times in request lifecycle especially in data iteration. Cache your questions list in a property, getter should just return the questions not load them.
Your list is sorted actually in apply request values phase but you return a new instance when a getter is called again in latter phases you the sorted list is gone during processing.
Upvotes: 4