First find the jar Packages You need to add to configure Ehcahe level two cache
hibernate-release-4.1.9.final→lib→ Ehcache-core-2.4.3.jar and Hibernate-ehcache-4.1.9.final.jar under optional→ehcache→ and slf4j-api-1.6.1.jar!.
Then from hibernate-release-4.1.9.final→project→etc→ copy the ehcache.xml to the src directory . put the cache . XML It's useless, it's all erased. , leave the final :
<ehcache>
<!-- Cache path --
<diskstore path= "E:\SecondCache"/>// self-configuration
<defaultcache
Maxelementsinmemory= "10000"
Eternal= "false"
Timetoidleseconds= "120"
Timetoliveseconds= "120"
Overflowtodisk= "true"
/>
</ehcache>
Then open and configure the cache in Hibernate.cfg.xml :
<!-- Turn on level two cache--
<property name= "Hibernate.cache.use_second_level_cache" >true</property>
<!--cache Provider--
<property name= "Hibernate.cache.region.factory_class" >
Org.hibernate.cache.ehcache.EhCacheRegionFactory
</property>
Finally, the cache is set in the XML file of the entity class : <cache usage= "Read-write"/>
such as :
<class name= "Cn.jnit.bean.User" table= "T_user" >
<cache usage= "Read-write"/>
<id name= "id" >
<generator class= "Sequence" >
</generator>
</id>
<property name= "pwd" ></property>
<property name= "Name" ></property>
<one-to-one name= "ud" class= "Cn.jnit.bean.UserDetail" cascade= "All" ></one-to-one>
</class>
If the query is a collection : You also need to set it in <SET> :
<class name= "cn.jbit.bean.Dept" table= "Dept" >
<cache usage= "Read-write"/>
<id name= "Deptno" >
<generator class= "sequence" ></generator>
</id>
<property name= "Dname" ></property>
<property name= "Loc" ></property>
<set name= "Emps" cascade= "Save-update" inverse= "true" order-by= "Empno desc"
Lazy= "false" >
<cache usage= "Read-only"/>
<key column= "Deptno" ></key>
<one-to-many class= "Cn.jbit.bean.Emp"/>
</set>
</class>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
If there is no <set> in the configuration file, and you do not have to set the query statement optimization , you need to open the query cache →<!- - Open Query cache --
<property name= "Hibernate.cache.query_cache_factory" >true</property>
Here is the data I tested in a one-to-two relationship , remember :
Not iterator<user> iterator=ses.createquery (HQL). Setcacheable (True). List (). iterator ();
Iterator<user> iterator=ses.createquery (HQL). Setcacheable (True). Iterate ();
Session ses=hibernatesessionfactory.getsession ();
String hql= "from User";
list<user> list = Ses.createquery (HQL). Setcacheable (True). List ();
System.out.println (List.size ());
Hibernatesessionfactory.closesession ();
Ses=hibernatesessionfactory.getsession ();
iterator<user> Iterator = Ses.createquery (HQL). Setcacheable (True). Iterate ();
while (Iterator.hasnext ()) {
User user = (user) iterator.next ();
System.out.println (User.getid ());
}
Ses.close ();
Configuring Hibernate Level Two Cache