com.webbfontaine.valuewebb.cache.PersistenceUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.webbfontaine.valuewebb.cache.PersistenceUtil.java

Source

package com.webbfontaine.valuewebb.cache;

import org.hibernate.CacheMode;
import org.jboss.seam.persistence.HibernateSessionProxy;

import javax.persistence.EntityManager;

/**
 * Copyrights 2002-2010 Webb Fontaine
 * This software is the proprietary information of Webb Fontaine.
 * Its use is subject to License terms.
 * User: nigiyan
 * Date: Aug 2, 2010
 */

/**
 * created assuming that persistence provider is hibernate
 */
public class PersistenceUtil {

    /**
     * Removes entity from cache for current transaction/session.<br/>
     * Useful when it is necessary to be sure that queried entity is up to date (not from cache). So, to provide that,
     * entity should be removed from cache after updating.
     * <p/>
     * Before using this method consider entity's <a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e2298"><b>
     * Cache concurrency strategy</b></a>, since for sensitive caching no need for manual control.
     *
     * @param entityManager used to get SessionFactory
     * @param clazz         Class of entity
     * @param id            the id of entity
     * @see org.hibernate.SessionFactory#evict(Class, java.io.Serializable)
     * @see com.webbfontaine.valuewebb.action.CompanyHome#update()
     */
    public static void removeObjectFromCache(EntityManager entityManager, Class clazz, Long id) {
        ((org.jboss.seam.persistence.HibernateSessionProxy) entityManager.getDelegate()).getSessionFactory()
                .evict(clazz, id);
        //todo: need to test this one: ((Session) entityManager.getDelegate()).getSessionFactory().getCache().evictEntity(clazz, id);
    }

    /**
     * Calling this methods disables caching for current transaction/session.
     *
     * @param entityManager session's em
     */
    public static void disableCaching(EntityManager entityManager) {
        ((HibernateSessionProxy) entityManager.getDelegate()).getSessionFactory().getCurrentSession()
                .setCacheMode(CacheMode.IGNORE);
    }

    public static void setManualFlushMode(EntityManager entityManager) {
        ((HibernateSessionProxy) entityManager.getDelegate()).setFlushMode(org.hibernate.FlushMode.MANUAL);
    }

    public static org.hibernate.classic.Session getSession(EntityManager entityManager) {
        return ((HibernateSessionProxy) entityManager.getDelegate()).getSessionFactory().getCurrentSession();
    }
}