Hibernate 总述

本文深入探讨Hibernate框架的基础概念,包括其映射策略、继承映射、父子表映射及二级缓存的应用。提供了详细的配置示例,如使用ehcache作为缓存实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概述

Hibernate的话题讲N页也讲不完,这里只顺便记录一些。 

SpringSide对Hibernate 三个层次的封装见 SpringSide的Hibernate封装

1.1  参考资料

  1. Hibernate 3.2 GA版的官方参考手册最重要的参考资料。
  2. 满江红的Hibernate 3.2 GA参考手册中文翻译 
  3. 《Java Persitence  with Hibernate》Gavin King所著,800多页有点厚。
  4. Hibernate自带的单元测试也是很好的参考资料。

2.映射

  Hibernate参考手册最末的几个例子演示了集中最经典的映射模式。

  推荐Hibernate Annotation 形式的映射,详见Hibernate Annotation

2.1 继承映射

      参考Product表的映射,Book类继承于Product类,通过一个列来区分,也可以编写某种表达式来区分。
      同时参考Hibernate参考手册里 Author/Work 的Example

2.2 父子表映射

      参考Orders表的映射, Order-OrderItem-Product的经典三角关系 及Hibernate参考手册Parent/Child Example ,Customer/Order/Product Example。

      父子表的这种精要型的映射,通过自动生成一般是生成不出来的。 

3.二级缓存

    hibernate的session提供了一级缓存,在同一个session中对同一个id的对象load两次,并不会发送两条sql给数据库。但是session关闭的时候,一级缓存就失效了。

    二级缓存是SessionFactory级别的全局缓存,它底下可以使用不同的缓存类库,比如ehcache、oscache等,需要使用缓存实现方案。

    详细请看: hibernate二级缓存攻略

 3.1 基本设置

1. 如果需要特别设置ehcache的属性,把一个ehcache.xml 定义文件拷贝到class-path.

2. jdbc.properties加上

hibernate.cache.use_query_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

3. applicationContext.xml的 <property name="hibernateProperties">下加上

<prop key="hibernate.cache.use_query_cache">$ {hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">$ {hibernate.cache.provider_class}</prop>

3.2 Entity级二级缓存

   Entity二级缓存是把PO放进cache,缓存的key就是ID,value是POJO,不同于查询的缓存。

   Entity二级缓存在BookDao.get(3),和book.getCategory()的情况下都能用到,把category这样的小表完全cache到内存挺不错的。

在hbm文件中: 

<class name="Product" table="PRODUCT" dynamic-insert="true" dynamic-update="true">
<cache usage="nonstrict-read-write"/>
<id name="id" column="ID">
<generator class="native"/>
</id>

   如果你使用的二级缓存实现是ehcache的话,需要配置ehcache.xml ,否则就会使用ehcache默认的配置

<cache name="com.xxx.pojo.Foo" maxElementsInMemory="500" eternal="false" timeToLiveSeconds="7200" timeToIdleSeconds="3600" overflowToDisk="true" />

3.3 查询缓存

   上面的二级缓存是针对单个对象的,如果要对查询结果,则是用下面的语句

query.setCacheable(true);//激活查询缓存
query.setCacheRegion("myCacheRegion");//指定要使用的cacheRegion,可选

   cacheRegion是可选的,可以对使用的缓存进行特殊设置, 在ehcahe.xml里要补上下面的一段。

<cache name="myCacheRegion" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值