一 为什么需要二级缓存
因为一级缓存有限(生命周期短),所以我们需要二级缓存(SessionFactory缓存)来弥补这个问题。
二 二级缓存说明
1 需要配置
2 二级缓存是交给第三方去处理,常见的Hashtable,OSCache,EHCache
3 二级缓存的原理
4 二级缓存的对象可能放在内存,也可能放在磁盘
三 使用OsCache来演示二级缓存的使用
引入E:\hibernate-distribution-3.3.1.GA-dist\hibernate-distribution-3.3.1.GA\lib\optional\oscache中的包oscache-2.1.jar
1 步骤-配置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>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/users
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
<property name="show_sql">true</property>
<!-- 配置让hibernate自动创建关系模型(表) -->
<property name="hbm2ddl.auto">update</property>
<!-- 启动二级缓存 -->
<property name="cache.use_second_level_cache">true</property>
<!-- 指定使用哪种二级缓存 -->
<property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
<property name="hibernate.generate_statistics">true</property>
<mapping resource="com/hsp/domain/Student.hbm.xml" />
<mapping resource="com/hsp/domain/Department.hbm.xml" />
<!-- 指定哪个domain启用二级缓存 特别说明二级缓存策略:
1. read-only
2. read-write
3. nonstrict-read-write
4. transcational -->
<class-cache class="com.hsp.domain.Student" usage="read-write"/>
</session-factory>
</hibernate-configuration>
2 步骤-拷贝一个oscache.propertis配置文件,可以使用参考文档,这里我们可以对各个属性值作一个说明
该文件来源:E:\hibernate-distribution-3.3.1.GA-dist\hibernate-distribution-3.3.1.GA\project\etc
拷贝到src目录下
3 步骤-在*.hbm.xml文件中加入使用二级缓存的策略
<cache usage="read-write"/>
也可以直接在hibernate.cfg.xml配置:
<class-cache class="cn.hsp.domain.Users" usage="read-only" />
hibernate二级缓存策略
■ 只读缓存(read-only)
■ 读写缓存(read-write) [ 银行,财务软件]
■ 不严格读写缓存(nonstrict-read-write) [bbs 被浏览多少次]
■ 事务缓存(transactional)
4 步骤-增加测试代码
public static void main(String[] args) {
// TODO Auto-generated method stub
//通过获取一个sesion,让hibernate框架运行(config->加载hibernate.cfg.xml)
Session s=null;
Transaction tx=null;
try {
//我们使用基础模板来讲解.
s=HibernateUtil.openSession();
tx=s.beginTransaction();
Student stu1=(Student) s.get(Student.class, 1);//1->一级缓存
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
System.out.println("*********************************");
try {
//我们使用基础模板来讲解.
s=HibernateUtil.openSession();
tx=s.beginTransaction();
Student stu1=(Student) s.get(Student.class, 1);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
5 步骤-二级缓存的测试结果
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_, student0_.dept_id as dept3_0_0_ from Student student0_ where student0_.id=?
*********************************
6 二级缓存统计命中率
public static void main(String[] args) {
// TODO Auto-generated method stub
//通过获取一个sesion,让hibernate框架运行(config->加载hibernate.cfg.xml)
Session s=null;
Transaction tx=null;
try {
//我们使用基础模板来讲解.
s=HibernateUtil.openSession();
tx=s.beginTransaction();
//查询45号学生
Student stu1=(Student) s.get(Student.class, 1);//1->一级缓存
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
System.out.println("*********************************");
try {
//我们使用基础模板来讲解.
s=HibernateUtil.openSession();
tx=s.beginTransaction();
//查询45号学生
Student stu1=(Student) s.get(Student.class, 1);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
//完成一个统计,统计信息在SessionFactory中
//SessionFactory
Statistics statistics=HibernateUtil.getSessionFactory().getStatistics();
System.out.println(statistics);
System.out.println(statistics.getSecondLevelCachePutCount());
System.out.println(statistics.getSecondLevelCacheHitCount());
System.out.println(statistics.getSecondLevelCacheMissCount());
}
7. 测试结果
Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_, student0_.dept_id as dept3_0_0_ from Student student0_ where student0_.id=?
*********************************
Statistics[start time=1508422796015,sessions opened=2,sessions closed=2,transactions=2,successful transactions=2,optimistic lock failures=0,flushes=2,connections obtained=2,statements prepared=1,statements closed=1,second level cache puts=1,second level cache hits=1,second level cache misses=1,entities loaded=1,entities updated=0,entities inserted=0,entities deleted=0,entities fetched=0,collections loaded=0,collections updated=0,collections removed=0,collections recreated=0,collections fetched=0,queries executed to database=0,query cache puts=0,query cache hits=0,query cache misses=0,max query time=0]
1
1
1