Is there a way to fetch Associated Entity from second level Cache instead of hitting the DB in Hibernate?

20 Views Asked by At

Suppose I have two entities : StudentDO and ParamDO. ParamDO is an entity that contains parameter code & values that are used throughout the application. I have already cached this entity using EhCache as Second Level Cache.

@Entity
@Table(name="PARAM")
@jakarta.persistence.Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class ParamDO
{
   @Column(name="TYPE") 
   private String type;

    @Column(name="CODE")
    private String code;

    @Column(name="VALUE")
    private String value;

}

`

Student Entity is associated to Param like this :

@Entity
@Table(name="STUDENT")
class StudentDO
{

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "SUBJECT_ID")
    private ParamDO subject;
}

`

My problem is despite caching the ParamDO , on querying StudentDO , associated ParamDO entity is still being fetched from DB. Is there a way this can be prevented?

I have already set these properties in application.yml -

spring.jpa.properties.hibernate.cache:
    use_second_level_cache: true
    use_query_cache: true

From the logs I can see that a cache is created for ParamDO in EhCache. What am I missing?

0

There are 0 best solutions below