Hibernate4 + Ehcache 例子

这是个hibernate + ehcache的例子,目前使用最新的hibernate-core.4.1.7.Final.jar + ehcache-core.2.6.0.jar

数据库使用的是mysql.

 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property> 
 

数据库脚本文件/src/main/resources/sql/*.sql

hibernate配置文件有:

1、/src/main/resources/hibernate.cfg.xml

2、/src/main/resources/ehcache.xml

datamapping 文件有:

1、/src/main/demo.pojo/Airport.hbm.xml

扫描二维码关注公众号,回复: 794005 查看本文章

2、/src/main/demo.pojo/Country.hbm.xml

3、/src/main/demo.pojo/Employee.hbm.xml

4、/src/main/demo.pojo/Language.hbm.xml

详细请看附件的例子,数据库配置好后可以直接运行。

运行结果:

1、CountryDAOTest.java

测试代码:

CountryDAO dao = new CountryDAO();
		for(int i = 1; i <= 5; i++) {
			Transaction tx = SessionManager.getSession().beginTransaction();
			TestTimer timer = new TestTimer("testGetCountries");
			List countries = dao.getCountries();
			tx.commit();
			timer.done();
			SessionManager.closeSession();
			assertNotNull(countries);
			assertEquals(countries.size(),229);			
		}

DAO代码:

	public List getCountries() {
		return SessionManager.currentSession()
							 .createQuery(
							  "from Country as c order by c.name")
							  .setCacheable(true)
							  .list();
	}

注意:只有.setCacheable(true) ,此时的查询结果才会缓存,否则不会缓存。

Country.hbm.xml配置如下:

<hibernate-mapping package="demo.pojo">
    <class name="Country" table="COUNTRY" dynamic-update="true">
		<meta attribute="implement-equals">true</meta>    
  		<cache usage="read-only"/> <!-- 必须配置 -->

        <id name="id" type="long" unsaved-value="null" >
            <column name="cn_id" not-null="true"/>
            <generator class="increment"/>
        </id>

	   <property column="cn_code" name="code" type="string"/>
	   <property column="cn_name" name="name" type="string"/>

	  <set name="airports" >
		<cache usage="read-only"/>
	    <key column="cn_id"/>
	    <one-to-many class="Airport"/>
	  </set>
    </class>
</hibernate-mapping>
 

输出如下:

可以看到查询语句只执行一次,其他4次的数据全部从缓存中获取。

Hibernate: select country0_.cn_id as cn1_0_, country0_.cn_code as cn2_0_, country0_.cn_name as cn3_0_ from COUNTRY country0_ order by country0_.cn_name
testGetCountries : 281 ms.
testGetCountries : 16 ms.
testGetCountries : 31 ms.
testGetCountries : 0 ms.
testGetCountries : 16 ms.

猜你喜欢

转载自ligf06.iteye.com/blog/1711161