ustun
ustun

Reputation: 7021

Avoiding redundant DB queries in JSF and conditionally rendering a ui:repeat

I am using JSF and Hibernate in my application. Say I have a user account, whose questions I want to display using <ui:repeat>, in a <ul> unordered list. I don't want to render the list if there are no questions, and display "No questions" text instead. The way I currently account is the following:

<ul>
<ui:repeat value="#{user.questions}" var="question">
    <li>#{question.text}</li>
</ui:repeat>
</ul>

<h:outputText rendered=#{user.questions.size() == 0}">no questions</h:outputText>

There are two problems with this, the stray <ul> tags if there are no questions.

Should I encapsulate it in another panel with again rendered=#{user.questions.size() > 0} because it seems ui:repeat does not accept rendered property.

The second problem is that user.questions.size() is calculated twice (and user.questions is accessed in two different places), does that mean two hits for the same variable in db?

Upvotes: 0

Views: 293

Answers (1)

McDowell
McDowell

Reputation: 108899

Should I encapsulate it in another panel with again rendered=#{user.questions.size() > 0} because it seems ui:repeat does not accept rendered property.

Yes.

The second problem is that user.questions.size() is calculated twice (and user.questions is accessed in two different places), does that mean two hits for the same variable in db?

Such behaviour should be handled in your model by appropriately scoping and caching the data.

@ManagedBean @RequestScoped
public class DemoBean {

  private List<Question> questions;

  public List<Question> getQuestions() {
    if(questions == null) {
      questions = lookupQuestions();
    }
    return questions;
  }

  // etc.

Upvotes: 1

Related Questions