Category.java代码:
package com.jlee07.cache;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
/**
* @author JLee
* 板块
*/
@Entity
@Table(name="Category")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE ,region="jleeCache")
public class Category {
private int id ;
private String name ;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Msg.java代码:
package com.jlee07.cache;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="Msg")
public class Msg {
private int id ;
private String cont ;
private Topic topic ;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="cont" , length=500)
public String getCont() {
return cont;
}
public void setCont(String cont) {
this.cont = cont;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="topicId")
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
}
Topic.java代码:
package com.jlee07.cache;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Administrator
* 主题
*/
@Entity
@Table(name="topic")
@NamedQueries({
@NamedQuery(name="Topic.selectTopic" , query="from Topic t where t.id = :id ") ,
@NamedQuery(name="Topic.conditionTopic" , query="from Topic t where t.title like :title ")
})
//hibernate3.3.2尚未支持
//@NamedNativeQueries({
// @NamedNativeQuery(name="native_sql_page" , query="select * from topic limit 2,5")
//})
public class Topic {
private int id ;
private String title ;
private Date createDate ;
public Date getCreateDate() {
return createDate;
}
@Column(name="createDate")
@Temporal(TemporalType.DATE)
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
private Category category ;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="title" , length=32)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="categoryId")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
HibernateCacheTest.java代码:
package com.jlee07.cache;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class HibernateCacheTest {
private static SessionFactory sf ;
@BeforeClass
public static void beforeClass(){
sf = new AnnotationConfiguration().configure().buildSessionFactory() ;
}
@AfterClass
public static void afterClass(){
sf.close() ;
}
/**
* 使用 session 级缓存
*/
@Test
public void testCache1(){
Session session = sf.getCurrentSession() ;
session.beginTransaction() ;
Category category = (Category)session.load(Category.class, 1) ;
System.out.println(category.getName());
Category category2 = (Category)session.load(Category.class, 1) ;
System.out.println(category2.getName());
session.getTransaction().commit() ;
}
/**
* load 和 iterate 默认使用二级缓存
* list 默认往二级缓存加数据,但查询的时候不使用缓存
* 如果要query使用二级缓存,需要打开查询缓存
* 查询缓存依赖 二级缓存 使用查询缓存需要开启二级缓存
*/
@Test
public void testCache2(){
Session session = sf.getCurrentSession() ;
session.beginTransaction() ;
Category category = (Category)session.load(Category.class, 1) ;
System.out.println(category.getName());
session.getTransaction().commit() ;
Session session2 = sf.getCurrentSession() ;
session2.beginTransaction() ;
Category category2 = (Category)session2.load(Category.class, 1) ;
System.out.println(category2.getName());
session2.getTransaction().commit() ;
}
/**
* 使用查询缓存
*/
@Test
public void testQueryCache(){
Session session = sf.getCurrentSession() ;
session.beginTransaction() ;
List<Category> categories = (List<Category>)session.createQuery("from Category ")
.setCacheable(true).list() ;
List<Category> categories2 = (List<Category>)session.createQuery("from Category ")
.setCacheable(true).list() ;
session.getTransaction().commit() ;
}
@Test
public void testSchemaExport(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
}
hibernate.cfg.xml文件:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">100</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <property name="cache.use_second_level_cache">true</property> <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="cache.use_query_cache">true</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!--<property name="hbm2ddl.auto">create</property>--> <mapping class="com.jlee07.cache.Category"/> <mapping class="com.jlee07.cache.Msg"/> <mapping class="com.jlee07.cache.Topic"/> </session-factory> </hibernate-configuration>
ehcache.xml文件:
<ehcache> <!-- Sets the path to the directory where cache .data files are created. If the path is a Java System Property it is replaced by its value in the running VM. The following properties are translated: user.home - User's home directory user.dir - User's current working directory java.io.tmpdir - Default temp file path --> <!-- dui xiang yi chu hou fang zhi de di fang --> <diskStore path="java.io.tmpdir"/> <!--Default Cache configuration. These will applied to caches programmatically created through the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used if the element is not eternal. Idle time is now - last accessed time timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used if the element is not eternal. TTL is now - creation time overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit. --> <!-- mo ren cache de pei zhi maxElementsInMemory : she zhi huan cun zhong zui duo fang zhi duo shao ge dui xiang eternal : bu mie de yong yuan sheng cun de(yong yuan bu qing chu huan cun zhong de dui xiang) timeToIdleSeconds : she zhi zui da de xian zhi shi jian timeToLiveSeconds : she zhi zui da de sheng cun shi jian(wei le he shu ju ku zuo tong bu ) overflowToDisk : yi chu de shi hou fang dao ying pan shang mian qu --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="1200" overflowToDisk="true" /> <!--Predefined caches. Add your cache configuration settings here. If you do not have a configuration for your cache a WARNING will be issued when the CacheManager starts The following attributes are required for defaultCache: name - Sets the name of the cache. This is used to identify the cache. It must be unique. maxInMemory - Sets the maximum number of objects that will be created in memory eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used if the element is not eternal. Idle time is now - last accessed time timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used if the element is not eternal. TTL is now - creation time overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit. --> <!-- Sample cache named sampleCache1 This cache contains a maximum in memory of 10000 elements, and will expire an element if it is idle for more than 5 minutes and lives for more than 10 minutes. If there are more than 10000 elements it will overflow to the disk cache, which in this configuration will go to wherever java.io.tmp is defined on your system. On a standard Linux system this will be /tmp" --> <!-- zi ding yi cache mo ren de cache shi bi xu de --> <cache name="jleeCache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="1200" overflowToDisk="true" /> <!-- Sample cache named sampleCache2 This cache contains 1000 elements. Elements will always be held in memory. They are not expired. --> <cache name="sampleCache2" maxElementsInMemory="1000" eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" /> <!-- Place configuration for your caches following --> </ehcache>