Hibernate 使用要点
Hibernate的话题讲N页也讲不完,这里只顺便记录一些。
1.映射
Hibernate参考手册最末的几个例子演示了集中最经典的映射模式
1.1 继承映射
参考Product表的映射,Book类继承于Product类,通过一个列来区分,也可以编写某种表达式来区分。
以及Hibernate参考手册里 Author/Work 的Example
1.2 父子表映射
参考Orders表的映射, Order-OrderItem-Product的经典三角关系 及Hibernate参考手册Parent/Child Example ,Customer/Order/Product Example。
父子表的这种精要型的映射,通过自动生成一般是生成不出来的。
2.二级缓存
hibernate的session提供了一级缓存,每个session,对同一个id进行两次load,不会发送两条sql给数据库,但是session关闭的时候,一级缓存就失效了。
二级缓存是SessionFactory级别的全局缓存,它底下可以使用不同的缓存类库,比如ehcache、oscache等,需要使用缓存实现方案。
详细请看 [hibernate二级缓存攻略{*}|http://www.javaeye.com/topic/18904]*
2.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>
2.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" />
2.3 查询缓存
query.setCacheable(true);query.setCacheRegion("myCacheRegion");
如果设置了cacheRegion,在ehcahe里要补一段
<cache name="myCacheRegion" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" />