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?
Caching in JPA is required within a transaction or within an extended persistence context to preserve object identity, but JPA does not require that caching be supported across transactions or persistence contexts. JPA 2.0 defines the concept of a shared cache.
The dynamic cache service plugs in as a level 2 cache provider to JPA. The L2 cache boosts the performance of your JPA application and you can configure and monitor the dynamic cache service for your JPA application in the WebSphere Application Server environment.
If we want to enable cache mechanism in a Spring Boot application, we need to add cache dependency in the pom. xml file. It enables caching and configures a CacheManager.
To enable the Spring Boot caching feature, you need to add the @EnableCaching annotation to any of your classes annotated with @Configuration or to the boot application class annotated with @SpringBootApplication .
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) {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With