1. 程式人生 > >hibernate手動更新資料 查詢資料與更新資料不同步

hibernate手動更新資料 查詢資料與更新資料不同步

最近在專案中,二級密碼驗證一直出問題,本來利用的是Ajax非同步提交驗證,程式剛才開始執行時候沒什麼問題,但是一旦使用者修改一下二級密碼之後,當再需要輸入二級密碼的時候就會一直驗證不成功,得到的密碼一直都是更新之前的資料,查了很久資料,才發現原來是由於快取的問題,由於JQuery 與ajax本身存在一定快取,hibernate也存在一級 與二級快取,所以導致手動更新後的資料一直不能與查詢資料同步。

解決方法:

  第一步 使jquery Ajax不快取

   在頁面上,在<head>之間加上

 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   

    在Action或者Servlet裡面,加上

  response.setHeader("Cache-Control", "no-cache, must-revalidate");
  response.setHeader("Pragma", "No-cache");
  response.setDateHeader("Expires", 0);

第二步 保持hibernate資料更新後session資料的同步

在執行hibernate updata或者save的時候,一定要使用事務,並且一定要commit();

    public void update(Member transientInstance) {
        Session session = getSession();
        Transaction tx = null;
        try {
         tx = session.beginTransaction();
            session.update(transientInstance);
            tx.commit();
        } catch (RuntimeException re){
            tx.rollback();
            throw re;
        }finally{
            session.close();
        }
    }

並且在查詢的時候,最好呼叫一下session的clear方法;

session.clear();

第三步 取消hibernate的二級快取

 在hibernate.cfg.xml裡面加上一條屬性

<property name="hibernate.cache.use_second_level_cache">false</property>

完成操作後重啟一下tomcat再次執行就可以了。