I am continuing from earlier question i raised (link below)
Spring MVC – Get reference data from database on server startup
After getting some advice on earlier post, the approach i think I can use to load reference data is, add below method in ArticleController (my controller class)
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
model.addAttribute("countryList", articleService.getCountryList());
model.addAttribute("skillsList", articleService.getSkillsList());
}
and then use hibernate second level cache like below,
@Entity
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Country {
...
}
similarly for Skill class
I have got three questions
- Will populateModel method (@ModelAttribute) get executed only once? i.e. before executing first @RequestMapping method on ArticleController class (for all requests in multiple sessions – I saw on log trace that ArticleController gets initialised when i start server)?
- Do i have to do anything more that what i have mentioned to achieve second level cache? (contry list and skills list is purely read only data in two separate tables)
- any imp point i missed and you can advice upon.
No. The method will be called for every request, as explained in the documentation. BTW, where would it find the request parameter (that you don’t use, BTW) if it was called only once?
If you don’t enable the query cache in addition to the second-level cache, and make the queries cachable, then Hibernate will execute a SQL query to load the country IDs from the database every time, and then load the entities themselves from the second-level cache. If the query cache is enabled and the queries are cachable, then Hibernate will execute a single query to load all the countries in the cache, and won’t execute any query anymore afterwards (at least, for the TTL of the cache region)
I think I have already done what I could do :-). You could read the following article for a better understanding.