简体   繁体   English

使用 JpaRepository 缓存

[英]Cache with JpaRepository

Hi I have extended a JpaRepository interface in following way.嗨,我以以下方式扩展了 JpaRepository 接口。

public interface StudentRepository extends JpaRepository<Student,Integer>
{
@Query(value= "SELECT s.id FROM student as s where s.createdat >  ADDDATE(CURRENT_DATE, :maxage ", nativeQuery = true )
public List<Integer> findWaitingStudentIds(@Param("maxage")int maxAge);
}

Here is the Entity class.这是Entity类。

@Entity(name="student ")
public class Student implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false)
    private Integer  id;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(updatable = false,insertable = false)
    private Date createdat;  
}

I want to add cache for "List findWaitingStudentIds" method.我想为“List findWaitingStudentIds”方法添加缓存。 How can I achieve this?我怎样才能做到这一点?

I can copy paste my answer from this StackOverflow question:我可以从这个 StackOverflow 问题中复制粘贴我的答案:

How should I implement a cache object/system in Spring? 我应该如何在 Spring 中实现缓存对象/系统?

Spring introduced abstraction for Cache in 3.x RELEASE. Spring 在 3.x RELEASE 中引入了对 Cache 的抽象。 You can read about it in official Spring documentation (the site is down today for some reason :)), or at this post for example.您可以在 Spring 的官方文档中阅读它(该站点由于某种原因今天关闭了 :)),或者在例如这篇文章中。

http://dzone.com/articles/spring-cache-abstraction-0 http://dzone.com/articles/spring-cache-abstraction-0

With this abstraction, all you need to do to enable cache is to add some annotations to your services, like通过这种抽象,启用缓存所需要做的就是向服务添加一些注释,例如

To add value to the cache为缓存添加值

@Cacheable("customers") public Customer findCustomer(long customerId) {...}

To remove value to the cache删除缓存中的值

@CacheEvict(value="customer", allEntries = true) public void removeAllCustomers(long customerId) {...}

You may consider reading the Hibernate Reference Manual .您可以考虑阅读Hibernate 参考手册 It helped me quite a lot when I used it for the very first time.当我第一次使用它时,它对我帮助很大。 It really clarify concepts and the way it works.它确实阐明了概念及其工作方式。

Some other answers are present in StackOverflow: Hibernate Cache Reference . StackOverflow: Hibernate Cache Reference中提供了其他一些答案。

Several quick tutorials are also available on the Web: Web 上还提供了几个快速教程:

I hope al this info helps you.我希望所有这些信息对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM