java 使用 JpaRepository 缓存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26837789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cache with JpaRepository
提问by user1516815
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. How can I achieve this?
我想为“List findWaitingStudentIds”方法添加缓存。我怎样才能做到这一点?
回答by mavarazy
I can copy paste my answer from this StackOverflow question:
我可以从这个 StackOverflow 问题中复制粘贴我的答案:
How should I implement a cache object/system in Spring?
Spring introduced abstraction for Cache in 3.x RELEASE. You can read about it in official Spring documentation (the site is down today for some reason :)), or at this post for example.
http://java.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) {...}
Spring 在 3.x RELEASE 中引入了对 Cache 的抽象。您可以在 Spring 的官方文档中阅读它(该站点今天由于某种原因关闭了 :)),或者例如在这篇文章中。
http://java.dzone.com/articles/spring-cache-abstraction-0
通过这种抽象,启用缓存所需要做的就是向服务添加一些注释,例如
为缓存添加值
@Cacheable("customers") public Customer findCustomer(long customerId) {...}
删除缓存中的值
@CacheEvict(value="customer", allEntries = true) public void removeAllCustomers(long customerId) {...}
回答by kazbeel
You may consider reading the Hibernate Reference Manual. It helped me quite a lot when I used it for the very first time. It really clarify concepts and the way it works.
您可以考虑阅读Hibernate 参考手册。当我第一次使用它时,它对我帮助很大。它确实阐明了概念及其工作方式。
Some other answers are present in StackOverflow: Hibernate Cache Reference.
StackOverflow: Hibernate Cache Reference中提供了其他一些答案。
Several quick tutorials are also available on the Web:
Web 上还提供了几个快速教程:
- Hibernate cache levels tutorial
- Hibernate Caching.
- Hibernate EHCache Second Level Caching Example Tutorial.
- ....
I hope al this info helps you.
我希望所有这些信息对您有所帮助。