网上有不少介绍hibernate二级缓存ehcache的配置,本文也不想重复。只是,对初学者,提出几点另外的建议。
1.jar包。
所需的jar包至少有hibernate(版本)包、ehcache-core-2.5.2.jar包、ehcache-web-2.0.4.jar包。或以上版本。
提供一个下载链接:
2.ehcache.xml文件如何创建或生成。
新建一个xml文件,用Basic Templetes 。有网友说hibernate.jar包里面也有,你去找吧。反正我没找到。Ehcache.xml属性配置,网上很多,这个只要拷一下就行。
3.ehcache.xml文件配置注意事项:
(1)仅有<defaultCache/>属性是可以的。在添加<cache name=”” />后,<defaultCache/>还是需要的。不然会报错:
Caused by: net.sf.ehcache.CacheException: Caches cannot be added by name when default cache config is not specified in the config. Please add a default cache config in the configuration.
(2)从映射文件.hbm.xml中的配置:
<cache usage="read-write" region="model 对象"/>
可知,Ehcache缓存的最小单位是对象。而如果仅设置对象中某些属性为缓存。比如一个User对象,它包含id,name,password三个字段,如果我仅想将name存为缓存,Ehcache好像无能为力。