Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache with JpaRepository

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?

like image 308
user1516815 Avatar asked Nov 10 '14 06:11

user1516815


People also ask

Does JPA have cache?

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.

What is L2 cache in JPA?

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.

How do I cache in spring boot?

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.

How do you register a cache engine with spring boot?

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 .


1 Answers

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) {...}
like image 155
mavarazy Avatar answered Oct 27 '22 08:10

mavarazy