JSF:绝对需要将昂贵的业务逻辑放在访问器方法中。如何避免称这个昂贵的BL倍数时间 [英] JSF: Absolutely need to put expensive Business Logic inside accessor method. How to avoid calling this expensive BL multiples time
问题描述
这是我的困境,我知道在JSF中访问器方法会多次调用,因此我知道不要在访问器方法中放置昂贵的业务逻辑(如DB访问)。如果我必须将业务逻辑放入我的访问器中该怎么办?在这种情况下我该怎么办?以下是我的困境的高层次布局。 (Mojarra 2.1,GF 3.1)
Here is my dilemma, I know in JSF the accessor method will get call mutilple times, therefore I know not to put expensive business logic (like DB access) in accessor method. What if I absolutely have to put business logic into my accessor. What should I do in this case? Below are a high level layout of my dilemma. (Mojarra 2.1, GF 3.1)
<h:dataTable value="#{myBean.comments}" var="item1">
<h:column>
#{item1.name} says: #{item1.comment}
<h:dataTable value="#{myBean.handleReplies(item1)}" var="item2">
<h:column>
#{item2.name} replies: #{item2.comment}
</h:column>
</h:dataTable>
</h:column>
</h:dataTable>
@ManagedBean
@ViewScoped
public void myBean(){
private List<Comment> comments;
@EJB
private MyEJB myEJB;
@PostConstruct
public void init(){
comments = myEJB.getAllComments();
}
//getters and setters for List<Comment> comments
public List<Comment> handleReplies(Comment comment){
//Return a List of replies of the comment
return myEJB.getRepliesFromComment(comment);
}
}
如你所见, inner
dataTable接受外部
dataTable的项
以生成其List。有没有办法以某种方式停止 handleReplies()
被多次调用,因为这个访问器方法访问DB。
As you can see, the inner
dataTable take in the item
of the outer
dataTable to generate its List. Is there a way for somehow stop handleReplies()
to be called multiple times, since this accessor method access DB.
推荐答案
如何使用 HashMap
创建视图范围的缓存?
How about using a HashMap
to create a view-scoped cache?
类似于:
private Map<Comment, List<Comment>> replies = new HashMap<Comment, List<Comment>>();
public List<Comment> handleReplies(Comment comment){
if (!replies.containsKey(comment)) {
replies.put(comment, myEJB.getRepliesFromComment(comment));
}
return replies.get(comment);
}
这样,您的视图范围的bean存储先前的请求结果,并返回它们如果请求已经完成。如果没有,则发出请求。最后,没有重复请求!
This way, your view-scoped bean store previous request results, and returns them if the request has already been done. If it hasn't, the request is made. In the end, no duplicate request!
这篇关于JSF:绝对需要将昂贵的业务逻辑放在访问器方法中。如何避免称这个昂贵的BL倍数时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!