如何配置二级缓存:
第一步:导入EHcache依赖
1)Maven项目:
org.hibernate hibernate-ehcache 4.3.10.Final
2)普通项目:
解压下载的hibernate压缩包,找到路径:\hibernate-release-4.3.10.Final\lib\optional\ehcache
,把路径下的包全部导入到项目
第二步:在源文件夹下,创建ehcache.xml
第三步:在hibernate.cfg.xml中配置
org.hibernate.cache.ehcache.EhCacheRegionFactory
如果是Spring+Hibernate,需要在spring.xml中
... org.hibernate.dialect.MySQLDialect true true update true true org.hibernate.cache.ehcache.EhCacheRegionFactory classpath:ehcache.xml
第四步:在需要缓存的对象中开启
若是使用hibernate注解:@Cache(usage =CacheConcurrencyStrategy.READ_ONLY)
@Entity@Table(name = "EMPLOYEE")@Cache(usage =CacheConcurrencyStrategy.READ_ONLY,include="all", region="") //开启缓存public class Employee { @Id //定义主键 @GeneratedValue(strategy=GenerationType.IDENTITY) //主键生成策略:自动选择mysql自增 @Column(name = "id") //对应数据库字段 private int id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "salary") private int salary; public Employee() { //@Entity规定必须有的构造方法 } //....getter //....setter}