mysql jpa缓存_【java框架】JPA(4) -- JPA二级缓存与JPQL

1.   JPA二级缓存配置

JPA中的二级缓存是在EntityManagerFactory中,但是默认EntityManagerFactory中的二级缓存是没有开启的,如果需要开启二级缓存需要做如下配置:

注:在hibernate4.3.8中是默认开启的二级缓存,无需配置;

步骤如下:

①    导入JPA二级缓存的jar包;

Jar包目录:

\hibernate-release-4.3.8.Final\lib\optional\ehcache\

ehcache-core-2.4.3.jar

hibernate-ehcache-4.3.8.Final.jar

slf4j-api-1.6.1.jar

b7569e0275fdd2f680377488329600b3.png

②    对应在persistence.xml中添加如下配置:

ENABLE_SELECTIVE

③    在对应的Entity类上加上注解:@Cacheable(true)

@Cacheable(true)

@Entitypublic classEmployee {

@Id

@GeneratedValueprivateLong id;private String name;

2.   JPA集合缓存配置

集合上面加上:@Cache(usage = CacheConcurrencyStrategy.READ_WRITE),就可以缓存这个集合

@OneToMany(fetch = FetchType.LAZY, mappedBy = "department")

@org.hibernate.annotations.Cache(usage=CacheConcurrencyStrategy.READ_WRITE)//注意:hibernate集合缓存一般不用,不需要配置,配置完之后性能更差//如果一定要配置集合缓存,集合中的对象也一定要能够放到缓存中

private Set employeeSet = new HashSet();

3.   JPA查询缓存配置

JPA查询缓存比较简单,只需要加上query1.setHint(QueryHints.HINT_CACHEABLE, true)即可。

Query query1 = entityManager.createQuery("select o from Employee o where o.id = ?");//把这个query1放到查询缓存中,也会到查询缓存中取

query1.setHint(QueryHints.HINT_CACHEABLE, true);

query1.setParameter(1, 1L);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值