天天看点

清空hibernate缓存

使用JPA查询数据量很大时,会造成内存溢出,我要调用清空hibernate缓存

/**
   * 清空session
   */
  public void clearSession() { 
      Session session = null; 
      try { 
       session = em.unwrap(Session.class); 

       if(session==null) { 
     
       } else { 
        session.clear(); 
       } 
      } catch(PersistenceException pe) { 
        pe.printStackTrace();
      } 
  } 
  /**
   * 清空二级缓存
   */
  public void clearCache()   { 
      Cache cache = null; 
      try { 
       SessionFactory sessionFactory = em.unwrap(Session.class).getSessionFactory(); 
       if(sessionFactory == null) { 
        
       }else {
         cache=sessionFactory.getCache();
           cache.evictAllRegions();//从所有缓存区域中逐出数据。
       }

      } catch (PersistenceException pe) { 
        pe.printStackTrace();
      } 
  } 
  /**
   *清理对象内存
   */
  private void  clear() {
     logger.info("开始清理对象内存>>>>>>>>>>>>>>>>>>>>");
     em.clear();//清空一级缓存
     clearCache(); //清空二级缓存
     clearSession(); //session
     logger.info("清理完成对象内存>>>>>>>>>>>>>>>>>>>>");
  }      

继续阅读