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

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;
				
			}
		});
	}