SSH(Spring + Struts + Hibernate)

Spring結合Hibernate

 

 

一、建立項目

(1)建立數據庫

DROP DATABASE mldn_hibernate;

 

CREATE DATABASE mldn_hibernate;

 

USE mldn_hibernate;

 

DROP TABLE news ;

 

CREATE TABLE news (

    id            int        primary key auto_increment ,

    title         VARCHAR(50)   not null,

    post_date     datetime   not null,

    abstractnote    VARCHAR(200)  not null,

    content           text       not null,

    imgurl          VARCHAR(50)

);

 

(2)項目:SpringHibernateDemo01

 

 

二、加入Spring和Hibernate的支持

注意:因爲現在是需要藉助Spring來管理或者組合其他框架,所以需要先加入Spring的支持。

1、加入Spring的支持

(1)項目—右鍵—MyEclipse—Add Spring Capabilities…

 

 

 

(2)加入Spring核心jar包以及和Hibernate結合需要的jar包

並且注意加入jar包的方式,還是選擇放到lib目錄下

 

 

 

(3)添加Spring的管理配置文件

一般採用默認名稱applicationContext.xml

 

 

 

(4)Finish完成

 

2、加入Hibernate的支持

 

(1)項目—右鍵—MyEclipse—Add Hibernate Capabilities…

 

 

 

(2)加入Hibernate的支持jar包

注意:比之前沒有使用Spring的時候多了一個jar包

 

 

 

(3)選擇Hibernate的配置文件

因爲此處使用了Spring,所以,選擇在已有的Spring的配置文件中進行Hibernate的配置

 

 

(4)選擇Spring的核心配置文件及填寫SessionFactory的ID

選擇是重新創建一個Spring的核心配置文件還是使用已經存在的,這裏使用已經存在的即可

並且填寫SessionFactory的ID,即定義SessionFactory的bean標籤的id值

 

(5)配置數據庫連接及數據源的bean的id

 

(6)是否由Hibernate自動創建SessionFactory類

取消選擇

 

 

(7)對於重複添加的jar的處理方式

選擇保留現有的或者替換都可以

 

 

3、查看加入Hibernate支持後Spring的applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

 

 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

       <property name="driverClassName"

           value="com.mysql.jdbc.Driver">

       </property>

       <property name="url"

           value="jdbc:mysql://localhost:3306/mldn_hibernate">

       </property>

       <property name="username" value="root"></property>

       <property name="password" value="mysqladmin"></property>

    </bean>

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       <property name="dataSource">

           <ref bean="dataSource"></ref>

       </property>

       <property name="hibernateProperties">

           <props>

              <prop key="hibernate.dialect">

                  org.hibernate.dialect.MySQLDialect

              </prop>

           </props>

       </property>

    </bean>

   

   

    </beans>

 

4、選擇數據源連接方式

(1)現在默認的是使用公用的數據源連接池的連接方式

使用該中方式,需要再加入commons-pool.jar ,否則會報找不到類的錯誤。

在Spring開發包的spring-framework-2.0-m3\lib\jakarta-commons中可以找到該jar包。

 

(2)使用c3p0方式進行數據源處理

需要修改Spring配置文件如下:

    <bean id="dataSource"

       class="com.mchange.v2.c3p0.DriverManagerDataSource">

       <property name="driverClass"

           value="org.gjt.mm.mysql.Driver">

       </property>

       <property name="jdbcUrl"

           value="jdbc:mysql://localhost:3306/testdb">

       </property>

       <property name="user" value="root"></property>

       <property name="password" value="mysqladmin"></property>

    </bean>

 

需要注意:當實現類繼承HibernateDaoSupport,並通過Spring注入了SessionFactory,使用該方法對於c3p0的連接池,可以直接通過getSession 進行處理,但如果使用common-pool的連接池則還需要手工關閉連接

 

5、加入Hibernate的show_sql屬性配置

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       <property name="dataSource">

           <ref bean="dataSource"></ref>

       </property>

       <property name="hibernateProperties">

           <props>

              <prop key="hibernate.dialect">

                  org.hibernate.dialect.MySQLDialect

              </prop>

              <prop key="hibernate.show_sql">

                  true

              </prop>

           </props>

       </property>

    </bean>

 

6、生成數據映射,建立pojo類

生成映射沒有變化

 

 

 

 

 

7、編寫dao

package mldn.lin.dao;

 

import java.util.List;

 

import mldn.lin.pojo.News;

 

public interface NewsDAO {

   

    public boolean doInsert(News news) throws Exception;

 

    public boolean doUpdate(News news) throws Exception;

 

    public boolean doRemove(int id) throws Exception;

 

    public List<News> findAll() throws Exception;

   

    public List<News> findAll(int cp,int ls,String keyword) throws Exception;

 

    public int getAllCount() throws Exception;

 

    public News findById(int id) throws Exception;

 

}

 

 

8、編寫實現類

三種結合的實現形式:

1、  手工編寫實現類,並定義SessionFactory屬性,但需要手工進行Session的打開關閉,而且需要通過Spring注入SessionFactory對象

2、  繼承HibernateDaoSupport,並通過Spring注入了SessionFactory,使用該方法對於c3p0的連接池,可以直接通過getSession 進行處理,但如果使用common-pool的連接池則還需要手工關閉連接。

3、  繼承HibernateDaoSupport,並注入了hibernateTemplate屬性,使用該方法可以完美的關閉和處理事務,但需要通過gethibernateTemplate來進行操作,而不能直接使用getSession進行處理。

 

第一種方法:手工編寫實現類(開發不用)

 

package mldn.lin.dao.impl;

 

import java.util.List;

 

import mldn.lin.dao.NewsDAO;

import mldn.lin.pojo.News;

 

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

 

public class NewsDAOImpl implements NewsDAO {

   

    private SessionFactory sessionFactory;

 

    public void setSessionFactory(SessionFactory sessionFactory) {

       this.sessionFactory = sessionFactory;

    }

 

    public boolean doInsert(News news) throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       session.save(news);

       session.beginTransaction().commit();

       session.close();

       return true;

    }

 

    public boolean doRemove(int id) throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       session.delete(findById(id));

       session.beginTransaction().commit();

       session.close();

       return true;

    }

 

    public boolean doUpdate(News news) throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       session.update(news);

       session.beginTransaction().commit();

       session.close();

       return true;

    }

 

    public List<News> findAll() throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       List all = session.createCriteria(News.class).list();

       session.close();

       return all;

    }

 

    public List<News> findAll(int cp, int ls, String keyword) throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       String hql="FROM News WHERE title=? OR abstractnote=? OR content=?";

       Query q=session.createQuery(hql);

       q.setString(0, "%"+keyword+"%");

       q.setString(1, "%"+keyword+"%");

       q.setString(2, "%"+keyword+"%");

       List<News> all=q.list();

       session.close();

       return all;

    }

 

    public News findById(int id) throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       News news=(News) session.get(News.class, id);

       session.close();

       return news;

    }

 

    public int getAllCount() throws Exception {

       // TODO Auto-generated method stub

       Session session=sessionFactory.openSession();

       String hql="SELECT count(*) FROM News";

       Query q=session.createQuery(hql);

       List all=q.list();

       int count=0;

       if(all!=null && all.size()>0){

           count=((Long)all.get(0)).intValue();

       }

       session.close();

       return count;

    }

}

 

實現類中定義sessionfactory屬性,需要使用Spring進行注入

將實現類配置到Spring管理中

    <bean id="newsdaoimpl" class="mldn.lin.dao.impl.NewsDAOImpl">

       <property name="sessionFactory">

           <ref bean="sessionFactory" />

       </property>

    </bean>

編寫測試類進行測試

package mldn.lin.test;

 

import mldn.lin.dao.NewsDAO;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test {

    public static void main(String[] args){

       ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

       NewsDAO newsdao=(NewsDAO) ctx.getBean("newsdaoimpl");

      

       try {

           System.out.println(newsdao.getAllCount());

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

      

    }

}

 

雖然這樣可以使Spring結合hibernate進行開發,但是還需要用戶自行編寫Session的打開關閉、事務處理。

 

 

第二種方法:使用Spring中提供好的HibernateDaoSupport支持類

如果要解決以上問題,可以使用Spring中提供好的HibernateDaoSupport支持類來完成

 

編寫實現類:

package mldn.lin.dao.impl;

 

import java.util.List;

 

import mldn.lin.dao.NewsDAO;

import mldn.lin.pojo.News;

 

import org.hibernate.Query;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

public class NewsDAOImpl extends HibernateDaoSupport implements NewsDAO {

 

    public boolean doInsert(News news) throws Exception {

       // TODO Auto-generated method stub

       this.getSession().save(news);

       return true;

    }

 

    public boolean doRemove(int id) throws Exception {

       // TODO Auto-generated method stub

       this.getSession().delete(findById(id));

       return true;

    }

 

    public boolean doUpdate(News news) throws Exception {

       // TODO Auto-generated method stub

       this.getSession().update(news);

       return true;

    }

 

    public List<News> findAll() throws Exception {

       // TODO Auto-generated method stub

       return this.getSession().createCriteria(News.class).list();

    }

 

    public List<News> findAll(int cp, int ls, String keyword) throws Exception {

       // TODO Auto-generated method stub

       String hql="FROM News WHERE title=? OR abstractnote=? OR content=?";

       Query q=this.getSession().createQuery(hql);

       q.setString(0, "%"+keyword+"%");

       q.setString(1, "%"+keyword+"%");

       q.setString(2, "%"+keyword+"%");

       return q.list();

    }

 

    public News findById(int id) throws Exception {

       // TODO Auto-generated method stub

       return (News)this.getSession().get(News.class, id);

    }

 

    public int getAllCount() throws Exception {

       // TODO Auto-generated method stub

       String hql="SELECT count(*) FROM News";

       Query q=this.getSession().createQuery(hql);

       List all=q.list();

       int count=0;

       if(all!=null && all.size()>0){

           count=((Long)all.get(0)).intValue();

       }

       return count;

    }

}

 

 

繼承的類中定義sessionfactory屬性,需要使用Spring進行注入

將實現類配置到Spring管理中

    <bean id="newsdaoimpl" class="mldn.lin.dao.impl.NewsDAOImpl">

       <property name="sessionFactory">

           <ref bean="sessionFactory" />

       </property>

    </bean>

編寫測試類進行測試

package mldn.lin.test;

 

import mldn.lin.dao.NewsDAO;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test {

    public static void main(String[] args){

       ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

       NewsDAO newsdao=(NewsDAO) ctx.getBean("newsdaoimpl");

      

       try {

           System.out.println(newsdao.getAllCount());

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

      

    }

}

 

繼承HibernateDaoSupport,並通過Spring注入了SessionFactory,使用該方法對於c3p0的連接池,可以直接通過getSession 進行處理,但如果使用common-pool的連接池則還需要手工關閉連接。

第三種方法:使用HibernateTemplate類

 

實現類:

package mldn.lin.dao.impl;

 

import java.sql.SQLException;

import java.util.List;

 

import mldn.lin.dao.NewsDAO;

import mldn.lin.pojo.News;

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

public class NewsDAOImpl extends HibernateDaoSupport implements NewsDAO {

 

    public boolean doInsert(News news) throws Exception {

       // TODO Auto-generated method stub

       this.getHibernateTemplate().save(news);

       return true;

    }

 

    public boolean doRemove(int id) throws Exception {

       // TODO Auto-generated method stub

       this.getHibernateTemplate().delete(findById(id));

       return true;

    }

 

    public boolean doUpdate(News news) throws Exception {

       // TODO Auto-generated method stub

       this.getHibernateTemplate().update(news);

       return true;

    }

 

    public List<News> findAll() throws Exception {

       // TODO Auto-generated method stub

       return this.getHibernateTemplate().find("FROM News");

    }

 

    public List<News> findAll(final int cp, final int ls, final String keyword) throws Exception {

       // TODO Auto-generated method stub

       List all = this.getHibernateTemplate().executeFind(

              new HibernateCallback() {

                  public Object doInHibernate(Session session)

                         throws HibernateException, SQLException {

                     // TODO Auto-generated method stub

                     // 直接編寫查詢方法

                     Query q = session.createQuery("FROM News WHERE title=? OR abstractnote=? OR content=?");

                     q.setFirstResult((cp - 1)* ls);

                     q.setMaxResults(ls);

                     q.setString(0, "%"+keyword+"%");

                     q.setString(1, "%"+keyword+"%");

                     q.setString(2, "%"+keyword+"%");

                     return q.list();

                  }

              });

       return all;

 

    }

 

    public News findById(int id) throws Exception {

       // TODO Auto-generated method stub

       return (News) this.getHibernateTemplate().get(News.class, id);

    }

 

    public int getAllCount() throws Exception {

       // TODO Auto-generated method stub

       List all=this.getHibernateTemplate().find("SELECT count(*) FROM News");

       int count=0;

       if(all!=null && all.size()>0){

           count=((Long)all.get(0)).intValue();

       }

       return count;

    }

}

 

 

配置Spring管理文件

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">

       <property name="sessionFactory">

           <ref bean="sessionFactory"></ref>

       </property>

    </bean>

 

    <bean id="newsdaoimpl" class="mldn.lin.dao.impl.NewsDAOImpl">

       <property name="hibernateTemplate">

           <ref bean="hibernateTemplate"></ref>

       </property>

    </bean>

 

   

編寫測試類:

package mldn.lin.test;

 

import mldn.lin.dao.NewsDAO;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test {

    public static void main(String[] args){

       ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

       NewsDAO newsdao=(NewsDAO) ctx.getBean("newsdaoimpl");

       

//     try {

//         System.out.println(newsdao.getAllCount());

//     } catch (Exception e) {

//         // TODO Auto-generated catch block

//         e.printStackTrace();

//     }

       try {

           for (int i = 0; i < 100; i++) {

              System.out.println(newsdao.findAll());

           }

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

    }

}

 

 

三、HibernateTemplate類的使用說明

HibernateTemplate是對Session操作的封裝:

可以完成save()、update()、delete()所能完成的功能。

使用Query對象時,可以通過HQL的方式進行修改和刪除操作

而使用HibernateTemplate可以通過bulkUpdate()來完成修改和刪除功能,該方法有3個重載:

只傳入一個字符串參數:直接執行該HQL語句,返回影響的記錄數

傳入一個HQL和一個Object參數:當HQL中只有一個?參數時,使用該方法可以爲參數賦值,並執行修改或刪除。

傳入一個HQL和一個Object[]參數:當HQL中包含多個?參數時,使用該方法,按順序爲?賦值

 

    public boolean doRemove(int id) throws Exception {

       // TODO Auto-generated method stub

       String hql = "DELETE FROM News AS n WHERE n.id = ?" ;

       if (this.getHibernateTemplate().bulkUpdate(hql,id) > 0) {

           return true ;

       }

       return false;

    }

 

完成查詢功能時:

查詢全部(不包含參數的查詢):可以使用 find方法進行查詢,將HQL語句傳入,返回List類型

    public List<News> findAll() throws Exception {

       // TODO Auto-generated method stub

       return this.getHibernateTemplate().find("FROM News");

    }

如果包含?參數,則與bulkUpdate相同,可以通過傳入Object參數或Object數組參數來進行處理。

 

    public List<News> findAll() throws Exception {

       // TODO Auto-generated method stub

       return this.getHibernateTemplate().find("FROM News WHERE id = ?",3);

    }

 

如果HQL中使用的是:參數時,可以通過findByNamedParam進行查詢。

後面的兩個數組參數分別表示參數名和參數值,注意需要一一對應。

    public List<News> findAll() throws Exception {

       // TODO Auto-generated method stub

       return this.getHibernateTemplate().findByNamedParam(

              "FROM News WHERE id = :id", "id", 3);

    }

 

當對主鍵進行查詢時,可以使用get方法進行處理,使用的方法與session.get完全相同。

 

完成分頁查詢

可以使用findByCriteria或findByExample,但這兩個方法不是很靈活,如果要使用HQL方式進行查詢

可以通過使用execute或executeFind方法 ,自行編寫被封裝的session操作,但需要使用匿名內部類:

    public List<News> findAll(final int cp,final int ls) throws Exception {

       // TODO Auto-generated method stub

       List all = this.getHibernateTemplate().executeFind(

              new HibernateCallback() {

                  public Object doInHibernate(Session session)

                         throws HibernateException, SQLException {

                     // TODO Auto-generated method stub

                     // 直接編寫查詢方法

                     Query q = session.createQuery("FROM News");

                     q.setFirstResult((cp - 1)* ls);

                     q.setMaxResults(ls);

                     return q.list();

                  }

              });

       return all;

    }

需要聲明一個HibernateCallback對象,並在內部類中實現doInHibernate方法,在該方法中完成對session的操作,如果需要調用外部類的屬性,注意要將屬性設置成爲final。

 

除了分頁以外,還有一種情況需要使用內部類來完成查詢:

當出現延遲加載問題時,需要在內部類中調用級聯查詢(因爲只有在內部類中session並不會關閉)。

 

當使用HibernateTemplate查詢返回數字或數組(帶有select關鍵字的HQL),返回的數字類型爲Long或Double。

    public int getAllCount() throws Exception {

       // TODO Auto-generated method stub

       List all = this.getHibernateTemplate()

              .find("SELECT count(*) FROM News");

       if (all != null && all.size() > 0) {

           return ((Long) all.get(0)).intValue();

       }

       return 0;

    }

四、SSH聯合開發

 

建立項目,加入支持

加入支持的順序:

Spring à Hibernate 或 Struts

 

 

注意,多加入了Spring對web的支持jar包

 

 

完成後臺代碼

 

編寫接口和實現類,並將HibernateTemplate和實現類配置到applicationContext.xml中

    <!-- 定義HibernateTemplate的Bean -->

    <bean id="hibernateTemplate"

       class="org.springframework.orm.hibernate3.HibernateTemplate">

       <property name="sessionFactory">

           <ref bean="sessionFactory"></ref>

       </property>

    </bean>

 

    <bean id="newsdaoimpl" class="org.liky.dao.impl.NewsDAOImpl">

       <property name="hibernateTemplate">

           <ref bean="hibernateTemplate"></ref>

       </property>

    </bean>

編寫頁面代碼,建立連接,完成列表顯示

       <center>

           <a href="news.do?status=list">列表</a>

       </center>

 

建立Struts的Action與ActionForm

 

package org.liky.struts.action;

 

import java.util.List;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.actions.DispatchAction;

import org.liky.dao.NewsDAO;

import org.liky.struts.form.NewsForm;

 

 

public class NewsAction extends DispatchAction {

   

 

    private NewsDAO newsdao;

 

   

    public ActionForward list(ActionMapping mapping, ActionForm form,

           HttpServletRequest request, HttpServletResponse response) {

       NewsForm newsForm = (NewsForm) form;// TODO Auto-generated method stub

 

       List all = null;

       int allRecorders = 0;

       try {

           all = this.newsdao.findAll(newsForm.getCp(),newsForm.getLs());

           allRecorders = this.newsdao.getAllCount();

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

       request.setAttribute("all", all);

       request.setAttribute("allRecorders", allRecorders);

       request.setAttribute("cp", newsForm.getCp());

       request.setAttribute("ls", newsForm.getLs());

 

       return mapping.findForward("list");

    }

 

    public void setNewsdao(NewsDAO newsdao) {

       this.newsdao = newsdao;

    }

}

在Spring中加入Action的Bean配置

 

    <bean id="newsaction" class="org.liky.struts.action.NewsAction">

       <property name="newsdao">

           <ref bean="newsdaoimpl"></ref>

       </property>

    </bean>

顯示所有數據

    <center>

       <logic:iterate id="news" name="all" scope="request">

           ${news.title } -- ${news.postDate } <br>

       </logic:iterate>

    </center>

將commons-pool.jar拷貝到項目中

 

運行後發現出現空指針異常,newsdao沒有被初始化,原因是由於Struts的Action本身是由struts-config.xml中的type中設置的類型進行創建,創建方式爲Class.forName(包.類名).newInstance()。而沒有用到Spring。

 

需要在struts-config.xml中,加入以下配置:

 

加入一個spring的插件

 

    <plug-in

       className="org.springframework.web.struts.ContextLoaderPlugIn">

       <set-property property="contextConfigLocation" value="/WEB-INF/classes/applicationContext.xml"/>

    </plug-in>

該配置是爲了在讀取struts-config.xml時,可以找到spring的配置文件,用來創建Spring對象

 

還需要設置一個controller類,在讀取action配置時,使ActionServlet改爲通過Spring創建Action對象,而不是直接創建。

    <controller

        processorClass="org.springframework.web.struts.DelegatingRequestProcessor">

    </controller>

該配置可以在讀取Action 時,先在spring的配置文件中查找是否有與該action對應的Bean,如果有,則使用spring進行創建,如果沒有,需要通過new的方式直接創建。

 

修改spring中對於action的bean配置,spring與struts在查找對應關係時,通過path路徑進行查找

    <bean name="/news" class="org.liky.struts.action.NewsAction">

       <property name="newsdao">

           <ref bean="newsdaoimpl"></ref>

       </property>

    </bean>

 

以上配置完成後,啓動服務器測試

 

發現出現404錯誤,而且控制檯沒有錯誤信息提示。

將log4j.properties加入到項目中

 

發現啓動時出現了找不到方法的異常

原因在於asm-2.2.3.jar與asm.jar有衝突,其中觀察方法的參數,發現asm.jar爲需要用的jar包,應該刪除asm-2.2.3.jar包

 

補充:使用hibernate緩存

修改applicationContext.xml中sessionFactory的hibernate屬性配置,加入使用二級緩存

       <property name="hibernateProperties">

           <props>

              <prop key="hibernate.dialect">

                  org.hibernate.dialect.MySQLDialect

              </prop>

              <prop key="hibernate.show_sql">true</prop>

              <prop key="hibernate.cache.provider_class">

                  org.hibernate.cache.EhCacheProvider

              </prop>

              <prop key="hibernate.cache.use_query_cache">true</prop>

              <prop key="hibernate.cache.use_second_level_cache">

                  true

              </prop>

           </props>

       </property>

 

修改hbm.xml,加入使用緩存的方式

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

    Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

    <class name="org.liky.pojo.News" table="news" catalog="testdb">

        <cache usage="read-only"/>

        <id name="id" type="java.lang.Integer">

            <column name="id" />

            <generator class="native" />

        </id>

        <property name="title" type="java.lang.String">

            <column name="title" length="20" not-null="true" />

        </property>

        <property name="keyword" type="java.lang.String">

            <column name="keyword" length="10" not-null="true" />

        </property>

        <property name="content" type="java.lang.String">

            <column name="content" length="65535" not-null="true" />

        </property>

        <property name="postDate" type="java.util.Date">

            <column name="post_date" length="19" not-null="true" />

        </property>

    </class>

</hibernate-mapping>

 

加入ehcache.xml

<ehcache>

 

    <!-- 表示緩存文件所保存的臨時路徑,java.io.tmpdir表示JDK所臨時保存文件的路徑 -->

    <diskStore path="java.io.tmpdir"/>

 

 

    <!--

       以下爲默認緩存配置,如果沒有進行單獨的配置,使用該配置進行緩存的保存:

 

        maxInMemory       - 設置內存中可以創建pojo數據的最大數量(針對一個pojo)

        eternal           - 設置緩存中的數據是否永久存在.如果爲true,  當超過時間後,數據也不銷燬.

        timeToIdleSeconds - 設置從緩存對象創建後經過多長時間自動銷燬. 只有當eternal爲false時纔可以使用. 單位爲秒

        timeToLiveSeconds - 設置緩存對象經過一次查詢後,多長時間不再被查詢後自動銷燬(閒置時間).

        overflowToDisk    - 如果爲true,則當數據數量超出範圍後(InMemory中的範圍)後,是否保存到硬盤上(保存的位置在上面的diskStore中定義).

 

        -->

    <defaultCache

        maxElementsInMemory="10000"

        eternal="false"

        timeToIdleSeconds="600"

        timeToLiveSeconds="120"

        overflowToDisk="true"

        />

 

</ehcache>

 

在調用查詢前需要設置是否使用緩存操作

在spring中,這個設置可以在配置文件中完成

    <!-- 定義HibernateTemplate的Bean -->

    <bean id="hibernateTemplate"

       class="org.springframework.orm.hibernate3.HibernateTemplate">

       <property name="cacheQueries">

           <value>true</value>

       </property>

       <property name="sessionFactory">

           <ref bean="sessionFactory"></ref>

       </property>

    </bean>

修改HibenateTemplate的配置,加入使用緩存的設置屬性,值爲true

 

刪除項目中的ehcache-1.1.jar包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章