main banner

Development

A common JSF mistake

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:


Controller

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

Configuration

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


View

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


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.
JSF


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


a) Ugly Code.

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

JSF


b) 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.
JSF


Conclusion

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.


Luis M.

Luis is a Software Engineer with more than 10 years of experience in the Software Development sector. He was born in Monterrey, Mexico and some of his favorites things in life are playing videogames, reading about history & running like there is no tomorrow!.. Some say he is the prince that was promised but maybe Melisandre & Jon Snow disagree on that. He is proud to be part of the Inflection Point blogger crew.


Articles