hibernate学习笔记第七天

二级缓存配置
1.导入ehcache对应的三个jar包
ehcache/*.jar
2.配置hibernate使用二级缓存
2.1设置当前环境开始二级缓存的使用
<property name="cache.use_second_level_cache">true</property>
2.2设置使用的二级缓存种类
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
3.设置加入二级缓存的模型
方法一:
在hbm.xml文件中,设置类和关联关系对象是否使用二级缓存
<class name="cn.itcast.h3.query.hql.vo.TeacherModel" table="tbl_teacher">
***** <cache usage="read-write"/>
<id name="uuid" column="uuid">
<generator class="native" />
</id>

<property name="teacherName"/>
<property name="nick"/>

<set name="students">
***** <cache usage="read-write"/>
<key column="teacherUuid"/>
<one-to-many class="cn.itcast.h3.query.hql.vo.StudentModel"/>
</set>
</class>
方法二:
类级缓存的配置
<class-cache
usage="read-write"
class="cn.itcast.h3.query.hql.vo.TeacherModel"
/>

模型中的集合缓存的配置
<collection-cache
usage="read-write"
collection="cn.itcast.h3.query.hql.vo.TeacherModel.students"
/>
<class-cache
usage="read-write"
class="cn.itcast.h3.query.hql.vo.StudentModel"
/>
在进行集合缓存配置时,如果使用了某种集合,必须将该集合中的模型也配置到缓存中,
并且是类级缓存
4.二级缓存自身的配置
写在src目录下,ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="d:\cache-data"/>
<defaultCache
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="1200"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
5.自定义缓存级别设置
6.测试二级缓存的存在性
7.二级缓存中的数据格式
二级缓存中存储的是加载的数据的散装格式,散装数据
读取二级缓存时,每次创建一个全新的对象,并根据其中OID,查找到对应的属性数据,进行组装
8.验证SQL查询对缓存的影响
使用SQL查询的内容会加载到二级缓存中
使用SQL查询不读取二级缓存的数据,无论是否提供OID
9.添加的数据是不进入二级缓存的
10.删除的数据影响二级缓存中的对应数据
11.修改的数据影响二级缓存中的对应数据

关联集合数据二级缓存操作
1.关联集合数据也进入二级缓存
2.关联集合缓存里面存储的是每个对象的OID,而不是所有的数据,因此当类级缓存没有存储数据时
关联集合缓存中仅存OID,再次获取时,必须重新按照OID查找数据

Hibernate的更新操作
当执行DML格式更新数据库,而不是使用常规的更新时,此时可能影响的数据量过多
当再次读取二级缓存时,无论读取曾经修改过的模型的任意数据,全部重新加载
Query q = s.createQuery("update TeacherModel set teacherName=:teacherName where uuid = :uuid");
q.setString("teacherName", "测试更新1");
q.setLong("uuid", 4L);
q.executeUpdate();

查询缓存
查询缓存是将每次查询的SQL语句与查询的结果全部保存起来,一对一
查询缓存开启方式
cfg.xml
<property name="cache.use_query_cache">true</property>
针对某一次的查询设定是否使用查询缓存
Query q = ....
q.setCacheable(true);

Session管理
表现层
页面数据收集,将数据封装后,传递给逻辑层
逻辑层
组合业务功能,将数据传递给数据层
void 转账(){
事务开启
A转账到银行总账号 update
银行总账号转账到B update
事务提交
}
数据层
数据处理
update(){}

解决方案:
针对一次请求,创建一个Session对象
使用线程绑定Session就可以解决上述问题
1.配置cfg.xml,设置开启线程绑定Session
<property name="current_session_context_class">thread</property>
2.获取Session对象
Session s = HibernateUtil.getSf().getCurrentSession();

猜你喜欢

转载自www.cnblogs.com/xyhero/p/9348833.html