Issue
Hi I have extended a JpaRepository interface in following way.
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(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?
Solution
I can copy paste my answer from this StackOverflow question:
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://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) {...}
Answered By - mavarazy