본문 바로가기

Programming!

Spring Hibernate 2차 캐시 설정

  

Spring 에서 JPA 2차 캐시를 사용하면 "spring.jpa.properties.javax.persistence.sharedCache.mode" 속성을 이용해 캐싱 entity의 범위를 지정할 수 있다. (Default : ENABLE_SELECTIVE)


Value

Description

ALL

All entities are cached

NONE

Disable caching

ENABLE_SELECTIVE

Enable caching only for those entities which has @Cacheable(true)

DISABLE_SELECTIVE

Enable caching only for those entities which are not specified with @Cacheable(false)

UNSPECIFIED

Applies persistence provider-specific default behavior


근데 막상 spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE 이렇게 주고 특정 엔티티에 @Cacheable를 지정을 해도 캐시가 안되는 현상이 나타났다. 음...


@Cacheable

@Data

@Entity

@Table(name = "entity_table_name")

@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

public class Company {


    @Id

    @Column(name = "id")

    private Long id;


    @Column(name = "name")

    private String name;


    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "company")

    private List<Employee> employees;


"spring.jpa.properties.javax.persistence.sharedCache.mode=ALL"로 하면 정상 적용이 된다. 그러나 쓸데 없는 엔터티까지 디폴트 캐시로 적용되므로 제외.


음... 뭘까를 고민하던 중 아하!!! 그렇다.. OneToMany 양쪽 모두 캐시 설정이 있어야지! 

즉, Company에 @Cacheable이 있고, 자식 리스트에 @Cache를 적용했어도, 자식(Employee)  자체에도 @Cacheable을 적용해줘야 한다.

@Cacheable

@Data

@Entity

@Table(name = "entity_table_name")

@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

public class Employee {

...

    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

    @ManyToOne(fetch = FetchType.EAGER)

    @JoinColumn(name = "company_id", referencedColumnName = "id", insertable = false, updatable = false)

    private Company company;

...

}


Entity 하나에만 걸고싶다는 생각에 관계설정 무시한 댓가로 한시간은 날린 듯 싶다. 췟.