关于Layout中的数据请求的问题

Linuxboy 2010-12-23
在Layout组件中需要显示由数据库中读取的一个List:
@Inject
@property
private CatDao dao; //这是一个service
public List<Cat> getCatList(){
     return dao.findAll();
}


当我访问任何一个包含Layout组件的page的时候,dao.findAll()都会被执行一次。
要怎样才能做到Layout首次加载执行dao.findAll()一次,然后所有的page请求都不再执行这一语句?
fantify 2010-12-23
我想你这个需求最好放到service里完成,组件不应该这样用
superaxis 2010-12-24
@Inject  
@property  
private CatDao dao; //这是一个service  
@Cached
public List<Cat> getCatList(){  
     return dao.findAll();  
}



试试这个,另外,你的dao不需要页面使用,这个时候可以去掉@Property。


Linuxboy 2010-12-24
测试了一下:
@fantify
public class Cats {
  @Inject
  private CatDao dao;

  public List<cat> getCatsList(){
        return dao.findAll();
  }

}

然后放在AppModule.java中:
public class AppModule {
	public static void bind(ServiceBinder binder) {
              binder.bind(Cats.class);
}
}

最后在Layout中引用:
@Inject
@Property
private Cats cats;

Layout.tml使用:
${cats.catsList}
效果与我之前一样,每次访问页面都会向数据库请求一次。不知道应该如何修改?


@superaxis
@Cached也一样,同样会重复请求。
fantify 2010-12-26
我的意思是用最简单的方式来处理:自己维护数据缓存,跟tapestry没关系

public class Cats { 
   @Inject 
   private CatDao dao; 
   private List<cat> cache;  
   public List<cat> getCatsList(){ 
         if (cache == null) {
             cache = dao.findAll(); 
         }
         return cache;
   }  
}

当然经常有这种需求的话可以参考http://dmitrygusev.blogspot.com/2010/09/tapestry5-caching-method-results.html 里的service方法结果缓存
Global site tag (gtag.js) - Google Analytics