Java tutorial
/** * Copyright (c) 2005-2012 https://github.com/zhangkaitao * * Licensed under the Apache License, Version 2.0 (the "License"); */ package cn.guoyukun.spring.jpa.repository.hibernate; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.Cache; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.jpa.HibernateEntityManagerFactory; /** * ? jpa api ?hibernateapi * <p>User: * <p>Date: 13-5-23 ?6:24 * <p>Version: 1.0 */ public class HibernateUtils { /** * ?jpa EntityManager ? hibernate Session API * * @param em * @return */ public static Session getSession(EntityManager em) { return (Session) em.getDelegate(); } /** * ?jpa EntityManager ? hibernate SessionFactory API * * @param em * @return * @see #getSessionFactory(javax.persistence.EntityManagerFactory) */ public static SessionFactory getSessionFactory(EntityManager em) { return getSessionFactory(em.getEntityManagerFactory()); } /** * ?jpa EntityManagerFactory ? hibernate SessionFactory API * * @param emf * @return */ public static SessionFactory getSessionFactory(EntityManagerFactory emf) { //TODO: jetty?, TomcatOK HibernateEntityManagerFactory hef = (HibernateEntityManagerFactory) emf; // org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean a; SessionFactory sf = hef.getSessionFactory(); return sf; } /** * ? jpa EntityManager ?hibernate Cache API * * @param em * @return * @see #getCache(javax.persistence.EntityManagerFactory) */ public static Cache getCache(EntityManager em) { return getCache(em.getEntityManagerFactory()); } /** * ?jpa EntityManagerFactory ? hibernate Cache API * * @param emf * @return */ public static Cache getCache(EntityManagerFactory emf) { return getSessionFactory(emf).getCache(); } /** * * * @param em */ public static void evictLevel1Cache(EntityManager em) { em.clear(); } /** * ?jpa EntityManager * * @param em * @see #evictLevel2Cache(javax.persistence.EntityManagerFactory) */ public static void evictLevel2Cache(EntityManager em) { evictLevel2Cache(em.getEntityManagerFactory()); } /** * ?jpa EntityManagerFactory * 1? * 2?? * 3? * ? * jpa Cache api ?evict ? * * @param emf * @see org.hibernate.ejb.EntityManagerFactoryImpl.JPACache#evictAll() */ public static void evictLevel2Cache(EntityManagerFactory emf) { Cache cache = HibernateUtils.getCache(emf); cache.evictEntityRegions(); cache.evictCollectionRegions(); cache.evictDefaultQueryRegion(); cache.evictQueryRegions(); cache.evictNaturalIdRegions(); } }