Skip to main content

Software Development

A Common JSF mistake

Istock 1209869264

How to Build Code Which Prevents your Database from Receiving Too Many Hits

A couple of years ago I started working on a project that was being built around JSF (JavaServer Faces) and I started to notice that the Database was taking more hits than expected.

After digging around, I found out that when you access the Database in a method that is called in a UIData component, the DB takes more hits than expected; this is because the value expressions are resolved more than once during the JSF life cycle.

Basically every time a UIData value expression is resolved, the database takes a hit, and since it’s more than likely to happen more than once in the JSF life cycle, the database continues to receive unnecessary requests.

Thankfully there are a couple of ways to easily prevent this situation, this is a common example of a path you would normally follow to feed a UIData component:


This bean retrieves a list of games, the controller delegates the call to the database through a service called GameService.



Now we need to configure this class as a managed bean so we can inject the GameService instance in the controller.



And finally in our view we feed a UIData component through the getGameList method in GameController.


What’s Wrong with the Above Code?

Well in our controller we don’t have a way to control how many times the UIData value expression is resolved, and it will probably be resolved more than once.


From here there are two easy approaches to resolve this issue:

1. Ugly Code.

We simply create a variable which we will validate and in case this variable is null, we will make the call to the service.


2. Use @PostConstruct

If your application uses JSF 1.2 and above, you can use the @PostContruct annotation to initialize your list.

@PostConstruct guarantees that the method will be invoked only once in the bean’s life-cycle, which comes handy since it will prevent the very same issue we have been talking about.



Surely there are more alternatives to solve this little common mistake, but since JSF 1.2 provides an easier solution why not use it? In any case you can always use external libraries such as Seam or just a simple “if” statement to validate the state of the instance.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Perficient Latin America

More from this Author

Follow Us