Example usage for org.hibernate SessionFactory getCache

List of usage examples for org.hibernate SessionFactory getCache

Introduction

In this page you can find the example usage for org.hibernate SessionFactory getCache.

Prototype

@Override
Cache getCache();

Source Link

Document

Obtain direct access to the underlying cache regions.

Usage

From source file:nl.strohalm.cyclos.dao.BaseDAOImpl.java

License:Open Source License

/**
 * Evicts all second-level cache elements which could get stale on entity updates
 *//* w w w.  ja  v  a 2  s.c  om*/
protected void evictSecondLevelCache() {
    final SessionFactory sessionFactory = getSessionFactory();

    // If this DAO is cached, evict the collection regions, as we don't know which ones will point out to it
    if (hasCache) {
        synchronized (sessionFactory) {
            final Cache cache = sessionFactory.getCache();
            // We must invalidate all collection regions, as we don't know which other entities have many-to-many relationships with this one
            cache.evictCollectionRegions();
        }
    }

    // Evict the query cache region
    if (queryCacheRegion != null) {
        synchronized (sessionFactory) {
            final Cache cache = sessionFactory.getCache();
            cache.evictQueryRegion(queryCacheRegion);
        }
    }
}

From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java

License:Apache License

@AggrEventsTransactional
@Override//w ww  .  j a v  a 2  s .co  m
public void evictAggregates(Map<Class<?>, Collection<Serializable>> entitiesToEvict) {
    int evictedEntities = 0;
    int evictedCollections = 0;

    final Session session = getEntityManager().unwrap(Session.class);
    final SessionFactory sessionFactory = session.getSessionFactory();
    final Cache cache = sessionFactory.getCache();

    for (final Entry<Class<?>, Collection<Serializable>> evictedEntityEntry : entitiesToEvict.entrySet()) {
        final Class<?> entityClass = evictedEntityEntry.getKey();
        final List<String> collectionRoles = getCollectionRoles(sessionFactory, entityClass);

        for (final Serializable id : evictedEntityEntry.getValue()) {
            cache.evictEntity(entityClass, id);
            evictedEntities++;

            for (final String collectionRole : collectionRoles) {
                cache.evictCollection(collectionRole, id);
                evictedCollections++;
            }
        }
    }

    logger.debug("Evicted {} entities and {} collections from hibernate caches", evictedEntities,
            evictedCollections);
}

From source file:org.openmrs.test.BaseContextSensitiveTest.java

License:Mozilla Public License

/**
 * Method to clear the hibernate cache/*www .  jav  a  2  s  .c  o m*/
 */
@Before
public void clearHibernateCache() {
    SessionFactory sf = (SessionFactory) applicationContext.getBean("sessionFactory");
    sf.getCache().evictCollectionRegions();
    sf.getCache().evictEntityRegions();
}

From source file:org.openvpms.component.business.dao.hibernate.im.lookup.LookupReplacer.java

License:Open Source License

/**
 * Clears the second level caches of the specified persistent classes.
 *
 * @param persistentClasses the persistent classes
 * @param factory           the session factory
 */// w w w.  j  a v a2s  .  c  o m
private void clearCaches(Class[] persistentClasses, SessionFactory factory) {
    for (Class persistentClass : persistentClasses) {
        factory.getCache().evictEntityData(persistentClass);
    }
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

License:Open Source License

public static void clearCache(Class persistentClass, boolean evictQueries) {
    _RootDAO dao = new _RootDAO();
    org.hibernate.Session hibSession = dao.getSession();
    SessionFactory hibSessionFactory = hibSession.getSessionFactory();
    if (persistentClass == null) {
        for (Iterator i = hibSessionFactory.getAllClassMetadata().entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            String className = (String) entry.getKey();
            ClassMetadata classMetadata = (ClassMetadata) entry.getValue();
            try {
                hibSessionFactory.getCache().evictEntityRegion(Class.forName(className));
                for (int j = 0; j < classMetadata.getPropertyNames().length; j++) {
                    if (classMetadata.getPropertyTypes()[j].isCollectionType()) {
                        try {
                            hibSessionFactory.getCache().evictCollectionRegion(
                                    className + "." + classMetadata.getPropertyNames()[j]);
                        } catch (MappingException e) {
                        }//from ww w.ja v  a 2 s  .  c om
                    }
                }
            } catch (ClassNotFoundException e) {
            }
        }
        hibSessionFactory.getCache().evictEntityRegions();
        hibSessionFactory.getCache().evictCollectionRegions();
    } else {
        ClassMetadata classMetadata = hibSessionFactory.getClassMetadata(persistentClass);
        hibSessionFactory.getCache().evictEntityRegion(persistentClass);
        if (classMetadata != null) {
            for (int j = 0; j < classMetadata.getPropertyNames().length; j++) {
                if (classMetadata.getPropertyTypes()[j].isCollectionType()) {
                    try {
                        hibSessionFactory.getCache().evictCollectionRegion(persistentClass.getClass().getName()
                                + "." + classMetadata.getPropertyNames()[j]);
                    } catch (MappingException e) {
                    }
                }
            }
        }
    }
    if (evictQueries) {
        hibSessionFactory.getCache().evictQueryRegions();
        hibSessionFactory.getCache().evictDefaultQueryRegion();
    }
}

From source file:org.unitime.timetable.model.ExamType.java

License:Open Source License

public static void refreshSolution(Long sessionId, Long examTypeId) {
    org.hibernate.Session hibSession = ExamTypeDAO.getInstance().getSession();
    SessionFactory hibSessionFactory = hibSession.getSessionFactory();
    for (Long examId : (List<Long>) hibSession.createQuery(
            "select x.uniqueId from Exam x where x.session.uniqueId = :sessionId and x.examType.uniqueId = :examTypeId")
            .setLong("sessionId", sessionId).setLong("examTypeId", examTypeId).setCacheable(true).list()) {
        hibSessionFactory.getCache().evictEntity(Exam.class, examId);
        hibSessionFactory.getCache().evictCollection(Exam.class.getName() + ".assignedRooms", examId);
        hibSessionFactory.getCache().evictCollection(Exam.class.getName() + ".conflicts", examId);
    }/*from   ww  w.ja v a2s.  c o m*/
    for (Long eventId : (List<Long>) hibSession.createQuery(
            "select e.uniqueId from ExamEvent e inner join e.exam x where x.session.uniqueId = :sessionId and x.examType.uniqueId = :examTypeId")
            .setLong("sessionId", sessionId).setLong("examTypeId", examTypeId).setCacheable(true).list()) {
        hibSessionFactory.getCache().evictEntity(Event.class, eventId);
        hibSessionFactory.getCache().evictCollection(Event.class.getName() + ".meetings", eventId);
    }
    hibSessionFactory.getCache().evictDefaultQueryRegion();
}

From source file:org.unitime.timetable.model.Session.java

License:Open Source License

public void unlockOffering(InstructionalOffering offering, UserContext user) {
    OnlineSectioningServer server = getInstance();
    if (server != null) {
        server.execute(server.createAction(ReloadOfferingAction.class).forOfferings(offering.getUniqueId()),
                (user == null ? null/*ww  w  .  j av a2  s  .  c  o m*/
                        : OnlineSectioningLog.Entity.newBuilder().setExternalId(user.getExternalUserId())
                                .setName(user.getName()).setType(OnlineSectioningLog.Entity.EntityType.MANAGER)
                                .build()));
        server.unlockOffering(offering.getUniqueId());
    }
    try {
        SessionFactory hibSessionFactory = SessionDAO.getInstance().getSession().getSessionFactory();
        hibSessionFactory.getCache().evictEntity(InstructionalOffering.class, offering.getUniqueId());
        for (CourseOffering course : offering.getCourseOfferings())
            hibSessionFactory.getCache().evictEntity(CourseOffering.class, course.getUniqueId());
        for (InstrOfferingConfig config : offering.getInstrOfferingConfigs())
            for (SchedulingSubpart subpart : config.getSchedulingSubparts())
                for (Class_ clazz : subpart.getClasses())
                    hibSessionFactory.getCache().evictEntity(Class_.class, clazz.getUniqueId());
    } catch (Exception e) {
        Debug.error("Failed to evict cache: " + e.getMessage());
    }
}

From source file:org.unitime.timetable.model.Solution.java

License:Open Source License

public static void refreshSolution(Long solutionId) {
    SolutionDAO dao = new SolutionDAO();
    org.hibernate.Session hibSession = dao.getSession();
    SessionFactory hibSessionFactory = hibSession.getSessionFactory();
    hibSessionFactory.getCache().evictEntity(Solution.class, solutionId);
    hibSessionFactory.getCache().evictCollection(Solution.class.getName() + ".parameters", solutionId);
    hibSessionFactory.getCache().evictCollection(Solution.class.getName() + ".assignments", solutionId);
    for (Iterator i = hibSession
            .createQuery("select c.uniqueId from " + "Class_ c, Solution s where s.uniqueId=:solutionId and "
                    + "c.managingDept.uniqueId in elements (s.owner.departments)")
            .setLong("solutionId", solutionId.longValue()).iterate(); i.hasNext();) {
        Number classId = (Number) i.next();
        hibSessionFactory.getCache().evictEntity(Class_.class, classId);
        hibSessionFactory.getCache().evictCollection(Class_.class.getName() + ".assignments", classId);
    }/*from   w ww .j  a va 2  s .c  o  m*/
    hibSessionFactory.getCache().evictCollection(SolverGroup.class.getName() + ".solutions",
            (Long) hibSession.createQuery("select owner.uniqueId from Solution s where s.uniqueId=:solutionId")
                    .setLong("solutionId", solutionId).uniqueResult());
}

From source file:org.unitime.timetable.solver.jgroups.AbstractSolverServer.java

License:Apache License

@Override
public void refreshInstructorSolution(Collection<Long> solverGroupIds) {
    org.hibernate.Session hibSession = new _RootDAO().createNewSession();
    try {/* ww  w . ja  va  2  s .  c o  m*/
        SessionFactory hibSessionFactory = hibSession.getSessionFactory();
        List<Long> classIds = (List<Long>) hibSession.createQuery(
                "select distinct c.uniqueId from Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false")
                .setParameterList("solverGroupId", solverGroupIds).list();
        for (Long classId : classIds) {
            hibSessionFactory.getCache().evictEntity(Class_.class, classId);
            hibSessionFactory.getCache().evictCollection(Class_.class.getName() + ".classInstructors", classId);
        }
        List<Long> instructorIds = (List<Long>) hibSession.createQuery(
                "select i.uniqueId from DepartmentalInstructor i, SolverGroup g inner join g.departments d where "
                        + "g.uniqueId in :solverGroupId and i.department = d")
                .setParameterList("solverGroupId", solverGroupIds).list();
        for (Long instructorId : instructorIds) {
            hibSessionFactory.getCache().evictEntity(DepartmentalInstructor.class, instructorId);
            hibSessionFactory.getCache().evictCollection(DepartmentalInstructor.class.getName() + ".classes",
                    instructorId);
        }
        List<Long> requestIds = (List<Long>) hibSession.createQuery(
                "select distinct r.uniqueId from Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false")
                .setParameterList("solverGroupId", solverGroupIds).list();
        for (Long requestId : requestIds) {
            hibSessionFactory.getCache().evictEntity(TeachingRequest.class, requestId);
            hibSessionFactory.getCache()
                    .evictCollection(TeachingRequest.class.getName() + ".assignedInstructors", requestId);
        }
        List<Long> offeringIds = (List<Long>) hibSession.createQuery(
                "select distinct c.schedulingSubpart.instrOfferingConfig.instructionalOffering.uniqueId from "
                        + "Class_ c inner join c.teachingRequests r where c.controllingDept.solverGroup.uniqueId in :solverGroupId and c.cancelled = false")
                .setParameterList("solverGroupId", solverGroupIds).list();
        for (Long offeringId : offeringIds) {
            hibSessionFactory.getCache().evictEntity(InstructionalOffering.class, offeringId);
            hibSessionFactory.getCache().evictCollection(
                    InstructionalOffering.class.getName() + ".offeringCoordinators", offeringId);
        }
    } finally {
        hibSession.close();
    }
}

From source file:org.zanata.service.impl.CopyVersionServiceImplPerformanceTest.java

License:Open Source License

@After
public void tearDown() {
    log.debug("Shutting down EM");
    // clear second level cache
    SessionFactory sessionFactory = ((Session) em.getDelegate()).getSessionFactory();
    try {/*from w w  w.j  a  v  a 2  s  .  c  o  m*/
        sessionFactory.getCache().evictEntityRegions();
        sessionFactory.getCache().evictCollectionRegions();
    } catch (Exception e) {
        log.error(" *** Cache Exception " + e.getMessage());
    }
    em.getTransaction().rollback();
    if (em.isOpen()) {
        em.close();
    }
    em = null;
}