Spring MVC - 从二级缓存加载参考数据

时间:2012-12-02 12:59:37

标签: mysql hibernate spring-mvc drop-down-menu

我继续提出我之前提出的问题(链接如下)

Spring MVC - Get reference data from database on server startup

在之前的帖子上得到一些建议之后,我认为我可以用来加载参考数据的方法是,在ArticleController(我的控制器类)中添加以下方法

    @ModelAttribute
    public void populateModel(@RequestParam String number, Model model) {
        model.addAttribute("countryList", articleService.getCountryList());
        model.addAttribute("skillsList", articleService.getSkillsList());
    }

然后使用hibernate二级缓存,如下所示,

    @Entity
    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
    public class Country {
        ...
    }

类似于技能等级

我有三个问题

  1. populateModel方法(@ModelAttribute)只执行一次吗?即在对ArticleController类执行第一个@RequestMapping方法之前(对于多个会话中的所有请求 - 我在日志跟踪中看到,当我启动服务器时,ArticleController会被初始化)?
  2. 我必须做更多我所提到的实现二级缓存的事情吗? (contry list and skills list是两个单独的表中的纯粹只读数据)
  3. 我错过了任何一点,你可以提供建议。

2 个答案:

答案 0 :(得分:0)

  1. 没有。每个请求都会调用该方法,如the documentation中所述。顺便说一句,如果它只被调用一次,它会在哪里找到请求参数(你不使用,BTW)?

  2. 如果除了二级缓存之外没有启用查询缓存,并使查询可缓存,那么Hibernate每次都会执行SQL查询以从数据库加载国家ID,然后从二级缓存加载实体本身。如果启用了查询缓存并且查询是可缓存的,则Hibernate将执行单个查询以加载缓存中的所有国家/地区,之后不再执行任何查询(至少对于缓存区域的TTL)< / p>

  3. 我想我已经做了我能做的事:-)。您可以阅读the following article以便更好地理解。

答案 1 :(得分:0)

在回答问题1时,这种方法:

@ModelAttribute
    public void populateModel(@RequestParam String number, Model model) {
        model.addAttribute("countryList", articleService.getCountryList());
        model.addAttribute("skillsList", articleService.getSkillsList());
    }

标有@ModelAttribute注释。这意味着每次调用此控制器中的任何@RequestMapping带注释的方法时,都会执行该方法(之前)。

如果你要缓存一些模型属性,那么将它们作为@RequestMapping方法公开是更好的选择。

相关问题