Hibernate使用EHCache二级缓存
数据库结构:
create table teamEH (id varchar(32),teamname varchar(32));
create table studentEH (id varchar(32),name varchar(32),team_id varchar(32));
POJO:
package EHCache;
public class Student ...{
private String id; //标识id
private String name; //学生姓名
private Team team;//班级
public String getName() ...{
return name;
}
public void setId(String id) ...{
this.id = id;
}
public void setName(String stuName) ...{
this.name = stuName;
}
public String getId() ...{
return id;
}
public Student() ...{ //无参的构造函数
}
public Team getTeam() ...{
return team;
}
public void setTeam(Team team) ...{
this.team = team;
}
}
package EHCache;
import java.util.HashSet;
import java.util.Set;
public class Team ...{
private String id;
private Set students;
private String teamName;
public String getId() ...{
return id;
}
public void setId(String id) ...{
this.id = id;
}
public String getTeamName() ...{
return teamName;
}
public void setTeamName(String name) ...{
this.teamName = name;
}
public Set getStudents() ...{
return students;
}
public void setStudents(Set students) ...{
this.students = students;
}
}
Team.hbm.xml
其中[cache]标签表示对student集合缓存,但只缓存id,如果需要缓存student实例,则需要在student.hbm.xml中的
class标签中配置[cache]
[?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 - Hibernate Tools
--]
[hibernate-mapping package="EHCache" ]
[class name="EHCache.Team" table="teamEH" lazy="false"]
[id name="id" column="id"]
[generator class="uuid.hex"][/generator]
[/id]
[property name="teamName" column="teamName"][/property]
[set name="students"
lazy="true"
inverse="true"
outer-join="false"
batch-size="2"
cascade="save-update"
]
[!-- 对students集合缓存,但只是缓存student-id如果要对整个对象缓存,
还需要在Student.hbm.xml的class标签中加入[cache]标签 --]
[cache usage="read-write"/]
[key column="team_id"][/key]
[one-to-many class="EHCache.Student"/]
[/set]
[/class]
[/hibernate-mapping]
Student.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 - Hibernate Tools
--]
[hibernate-mapping package="EHCache" ]
[class name="EHCache.Student" table="studentEH" lazy="false"]
[cache usage="read-write"/]
[id name="id" column="id" unsaved-value="null"]
[generator class="uuid.hex"][/generator]
[/id]
[property name="name" column="name"][/property]
[many-to-one name="team"
column="team_id"
outer-join="true"
cascade="save-update"
class="EHCache.Team"][/many-to-one]
[/class]
[/hibernate-mapping]
Hibernate.cfg.xml
配置hibernate.cache.provider_class以启用EHCache
[?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"]
[!-- Generated by MyEclipse Hibernate Tools. --]
[hibernate-configuration]
[session-factory]
[property name="connection.username"]root[/property]
[property name="connection.url"]
jdbc:mysql://localhost:3306/schoolproject?characterEncoding=gb2312&useUnicode=true
[/property]
[property name="dialect"]
org.hibernate.dialect.MySQLDialect
[/property]
[property name="myeclipse.connection.profile"]mysql[/property]
[property name="connection.password"]1234[/property]
[property name="connection.driver_class"]
com.mysql.jdbc.Driver
[/property]
[property name="hibernate.dialect"]
org.hibernate.dialect.MySQLDialect
[/property]
[property name="hibernate.show_sql"]true[/property]
[property name="current_session_context_class"]thread[/property]
[property name="hibernate.cache.provider_class"]
org.hibernate.cache.EhCacheProvider
[/property]
[mapping resource="EHCache/Student.hbm.xml" /]
[mapping resource="EHCache/Team.hbm.xml" /]
[/session-factory]
[/hibernate-configuration]
EHCache.xml(放在classpath下)
[ehcache]
[diskStore path="c:\cache"/] [!--缓存文件存放位置--]
[defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/]
[cache name="EHCache.Student"
maxElementsInMemory="500" [!---超过500实例,就将多出的部分放置缓存文件中-]
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/] --]
[!-- Place configuration for your caches following --]
[/ehcache]
测试代码(插入准备数据部分)
package EHCache;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test ...{
public static void main(String[] args) ...{
String filePath=System.getProperty("user.dir")+File.separator+"src/EHCache"+File.separator+"hibernate.cfg.xml";
File file=new File(filePath);
SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
// Team team=new Team();
// team.setTeamName("team1");
//
//
// for(int i=0;i[1000;i++){
// Student stu=new Student();
// stu.setName("tom"+i);
// stu.setTeam(team);
// session.save(stu);
// }
// tx.commit();
//
}
}
测试成功后,运行以下代码
package EHCache;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test ...{
public static void main(String[] args) ...{
String filePath=System.getProperty("user.dir")+File.separator+"src/EHCache"+File.separator+"hibernate.cfg.xml";
File file=new File(filePath);
SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
//模拟多用户访问数据
Session session1=sessionFactory.openSession();
Transaction tx1=session1.beginTransaction();
List list=session1.createQuery("from Student").list();
for(int i=0;i[list.size();i++)...{
Student stu=(Student)list.get(i);
System.out.println(stu.getName());
}
tx1.commit();
session1.close();
Session session2=sessionFactory.openSession();
Transaction tx2=session2.beginTransaction();
//这个uuid从刚才插入的数据中复制一个student的id
Student stu=(Student)session2.get(Student.class, "4028818316d184820116d184900e0001");
System.out.println(stu.getName());
tx2.commit();
session2.close();
}
}
结果如下:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.id as id0_, student0_.name as name0_, student0_.team_id as team3_0_ from studentEH student0_
Hibernate: select team0_.id as id1_0_, team0_.teamName as teamName1_0_ from teamEH team0_ where team0_.id=?
tom0
tom1
tom2
tom3
tom4
tom5
tom6
tom7
tom8
tom9
tom10
........................................
tom974
tom975
tom976
tom977
tom978
tom998
tom999
Hibernate: select team0_.id as id1_0_, team0_.teamName as teamName1_0_ from teamEH team0_ where team0_.id=?
tom0
可以看到,第二次查询,已经不再访问数据库了,而且,查看c:\cache文件夹,也可以看到,数据已经缓存成功了
数据库结构:
create table teamEH (id varchar(32),teamname varchar(32));
create table studentEH (id varchar(32),name varchar(32),team_id varchar(32));
POJO:
package EHCache;
public class Student ...{
private String id; //标识id
private String name; //学生姓名
private Team team;//班级
public String getName() ...{
return name;
}
public void setId(String id) ...{
this.id = id;
}
public void setName(String stuName) ...{
this.name = stuName;
}
public String getId() ...{
return id;
}
public Student() ...{ //无参的构造函数
}
public Team getTeam() ...{
return team;
}
public void setTeam(Team team) ...{
this.team = team;
}
}
package EHCache;
import java.util.HashSet;
import java.util.Set;
public class Team ...{
private String id;
private Set students;
private String teamName;
public String getId() ...{
return id;
}
public void setId(String id) ...{
this.id = id;
}
public String getTeamName() ...{
return teamName;
}
public void setTeamName(String name) ...{
this.teamName = name;
}
public Set getStudents() ...{
return students;
}
public void setStudents(Set students) ...{
this.students = students;
}
}
Team.hbm.xml
其中[cache]标签表示对student集合缓存,但只缓存id,如果需要缓存student实例,则需要在student.hbm.xml中的
class标签中配置[cache]
[?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 - Hibernate Tools
--]
[hibernate-mapping package="EHCache" ]
[class name="EHCache.Team" table="teamEH" lazy="false"]
[id name="id" column="id"]
[generator class="uuid.hex"][/generator]
[/id]
[property name="teamName" column="teamName"][/property]
[set name="students"
lazy="true"
inverse="true"
outer-join="false"
batch-size="2"
cascade="save-update"
]
[!-- 对students集合缓存,但只是缓存student-id如果要对整个对象缓存,
还需要在Student.hbm.xml的class标签中加入[cache]标签 --]
[cache usage="read-write"/]
[key column="team_id"][/key]
[one-to-many class="EHCache.Student"/]
[/set]
[/class]
[/hibernate-mapping]
Student.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 - Hibernate Tools
--]
[hibernate-mapping package="EHCache" ]
[class name="EHCache.Student" table="studentEH" lazy="false"]
[cache usage="read-write"/]
[id name="id" column="id" unsaved-value="null"]
[generator class="uuid.hex"][/generator]
[/id]
[property name="name" column="name"][/property]
[many-to-one name="team"
column="team_id"
outer-join="true"
cascade="save-update"
class="EHCache.Team"][/many-to-one]
[/class]
[/hibernate-mapping]
Hibernate.cfg.xml
配置hibernate.cache.provider_class以启用EHCache
[?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"]
[!-- Generated by MyEclipse Hibernate Tools. --]
[hibernate-configuration]
[session-factory]
[property name="connection.username"]root[/property]
[property name="connection.url"]
jdbc:mysql://localhost:3306/schoolproject?characterEncoding=gb2312&useUnicode=true
[/property]
[property name="dialect"]
org.hibernate.dialect.MySQLDialect
[/property]
[property name="myeclipse.connection.profile"]mysql[/property]
[property name="connection.password"]1234[/property]
[property name="connection.driver_class"]
com.mysql.jdbc.Driver
[/property]
[property name="hibernate.dialect"]
org.hibernate.dialect.MySQLDialect
[/property]
[property name="hibernate.show_sql"]true[/property]
[property name="current_session_context_class"]thread[/property]
[property name="hibernate.cache.provider_class"]
org.hibernate.cache.EhCacheProvider
[/property]
[mapping resource="EHCache/Student.hbm.xml" /]
[mapping resource="EHCache/Team.hbm.xml" /]
[/session-factory]
[/hibernate-configuration]
EHCache.xml(放在classpath下)
[ehcache]
[diskStore path="c:\cache"/] [!--缓存文件存放位置--]
[defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/]
[cache name="EHCache.Student"
maxElementsInMemory="500" [!---超过500实例,就将多出的部分放置缓存文件中-]
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/] --]
[!-- Place configuration for your caches following --]
[/ehcache]
测试代码(插入准备数据部分)
package EHCache;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test ...{
public static void main(String[] args) ...{
String filePath=System.getProperty("user.dir")+File.separator+"src/EHCache"+File.separator+"hibernate.cfg.xml";
File file=new File(filePath);
SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
// Team team=new Team();
// team.setTeamName("team1");
//
//
// for(int i=0;i[1000;i++){
// Student stu=new Student();
// stu.setName("tom"+i);
// stu.setTeam(team);
// session.save(stu);
// }
// tx.commit();
//
}
}
测试成功后,运行以下代码
package EHCache;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test ...{
public static void main(String[] args) ...{
String filePath=System.getProperty("user.dir")+File.separator+"src/EHCache"+File.separator+"hibernate.cfg.xml";
File file=new File(filePath);
SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
//模拟多用户访问数据
Session session1=sessionFactory.openSession();
Transaction tx1=session1.beginTransaction();
List list=session1.createQuery("from Student").list();
for(int i=0;i[list.size();i++)...{
Student stu=(Student)list.get(i);
System.out.println(stu.getName());
}
tx1.commit();
session1.close();
Session session2=sessionFactory.openSession();
Transaction tx2=session2.beginTransaction();
//这个uuid从刚才插入的数据中复制一个student的id
Student stu=(Student)session2.get(Student.class, "4028818316d184820116d184900e0001");
System.out.println(stu.getName());
tx2.commit();
session2.close();
}
}
结果如下:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.id as id0_, student0_.name as name0_, student0_.team_id as team3_0_ from studentEH student0_
Hibernate: select team0_.id as id1_0_, team0_.teamName as teamName1_0_ from teamEH team0_ where team0_.id=?
tom0
tom1
tom2
tom3
tom4
tom5
tom6
tom7
tom8
tom9
tom10
........................................
tom974
tom975
tom976
tom977
tom978
tom998
tom999
Hibernate: select team0_.id as id1_0_, team0_.teamName as teamName1_0_ from teamEH team0_ where team0_.id=?
tom0
可以看到,第二次查询,已经不再访问数据库了,而且,查看c:\cache文件夹,也可以看到,数据已经缓存成功了