hiberante性能优化-启用二级缓存

参考资料:
hibernate 3.2 帮助文档 19.2节

1.在hibernate的属性文件中配置sessionFactory的属性,

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
//启用二级缓存
<prop key="hibernate.cache.use_second_level_cache">true</prop>
//ehcache的配置文件
<prop key="hibernate.cache.configurationResourceName">ehcache.xml</prop>
//启用查询缓存
<prop key="hibernate.cache.use_query_cache">true</prop>
//指定hibernate缓存实现为 ehcache
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>


2.ehcache.xml
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>
<defaultCache maxElementsInMemory="10000" eternal="true" overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="180" />
</ehcache>


3.使用注解配置实体
@Entity
@Table(name="T1_YP_LB")
//在实体上启用缓存 org.hibernate.annotations.CacheConcurrencyStrategy指定缓存的模式
@Cache(usage=org.hibernate.annotations.CacheConcurrencyStrategy.READ_ONLY)
public class YP_lb{

@OneToMany(mappedBy="yplb",fetch=FetchType.EAGER)
fetch
fetch 属性是 FetchType 类型的属性。可选择项包括:FetchType.EAGER 和 FetchType.LAZY。前者表示关联关系的从类在主类加载的时候同时加载,后者表示关联关

系的从类在自己被访问时才加载。默认值是 FetchType.EAGER。
@OneToMany默认类型为FetchType.LAZY
//在一对多的关系式指定缓存类别,这里说明一下虽然在实体上使用了缓存但是只会缓存实体的普通属性,对于集合要有自己的缓存区域
//指定lazy=false 当lazy=true时可能造成实体无法被缓存
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE,include="non-lazy")
public Set<YP_YLFL> getYlfls() {
return ylfls;
}
}


@Entity
@Table(name="T1_YP_YLFL_2")
@Cache(usage=org.hibernate.annotations.CacheConcurrencyStrategy.READ_ONLY)
public class YP_YLFL_2 implements Serializable {
//fetch 指定为eager标识使用lazy
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="FLID")
public YP_YLFL getFlid() {
return flid;
}

}


4.
数据库dao类的操作

public List<YP_lb> findAll() throws DataAccessException  {
String queryString = "from YP_lb";
return (List<YP_lb>)hibernateTemplate.execute(new HibernateCallback() {
public List<YP_lb> doInHibernate(Session session) throws HibernateException,
SQLException {
Query query=session.createQuery("from YP_lb lb");
//启用查询缓存
query.setCacheable(true);
List<YP_lb> lb=query.list();
return lb;

}
});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值