开发者

Hibernate loading strategy

We are utilizing the OpenSessionInView with our Spring MVC application. I am not sure how best to handle this situation. Mostly because I'm not deeply familiar with Hibernate. We have 2 objects which are loaded for each and every page we view. Let's pretend we are working on a CMS. So we have to load the person who is logged in on each and every page, and what site they are currently working on. During the normal course of operations none of this data really changes.

We have a custom interceptor which basically looks like this:

public class PersistenceInterceptor implements HandlerInterceptor {
    private PlatformTransactionManager transactionManager; //from spring
    private TransactionStatus transactionStatus;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
        if (handler instanceof SpecialInterface) {
           handler.setPerson(loadPersonByKey(session.getAttribute(PERSON_KEY)));
           handler.setSite(loadSiteByKey(session.getAttribute(S开发者_开发百科ITE_KEY)));
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //Wrapped in try catch & rolled back if unable to commit
        transactionManager.commit(transactionStatus);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if (ex != null && !transactionStatus.isCompleted()) {
            transactionManager.rollback(transactionStatus);
        }
    }

Would it be best for us to modify the way we are going about this, and just slightly modify this to use our configured Hibernate sessionFactory to get the session, and then update the person & site -- or would we still be loading these values?

Obviously these queries are not that heavyweight, but there are times where it would be useful to save other things which are a bit heavier to try and offload work from the DB.


If your goal is to offload work from the DB, then you should think about using a second-level cache. Since the same persons and sites are very often read and rarely updated, a second-level cache for these entities is very well suited, and will effectively reduce the number of times these entities are loaded, without having to change anything in your code.

See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-cache

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜