Hibernate 2L writes the active Entity to the cache, but it still queries from the database every time.

I use Spring Boot 3.2.2 and hibernate version: 6.4.1, I am using Redis cache actively. I’m trying to activate the Hibernate 2L Cache. as I mentioned, it writes to CACHE, but it still pulls it from the database every time.

<dependency>
                <groupId>org.redisson</groupId>
                <artifactId>redisson-hibernate-6</artifactId>
                <version>3.27.2</version>
            </dependency>

application.properties

spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.factory_class=org.redisson.hibernate.RedissonRegionFactory

redisson.yaml

singleServerConfig:
  address: "redis://redis.payment:27000"

My UserType Entity

@Entity
@Table(name = "USERTYPE")
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class UserType extends BaseEntity implements Serializable {
    @Id
    @Column
    private Long id;

    @OneToMany(mappedBy = "userType", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private List<UserTypeTranslate> translateList;
}

My UserTypeTranslate Entity

@Entity
@Table(name = "USERTYPETRANSLATE")
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class UserTypeTranslate extends LanguageEntity implements Serializable {

    @Id
    @Column(name = "ID")
    private Long id;

    @Column
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USERTYPEID", referencedColumnName = "ID")
    private UserType userType;

}

My Repository class

import com.payment.data.domain.UserType;
import com.payment.data.repository.ParameterEntityRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserTypeRepository
        extends ParameterEntityRepository<UserType, Long>, JpaSpecificationExecutor<UserType> {
    
}

My Business Service

    public List<UserTypeDto> findAllUserType() {
        List<UserTypeDto> resultList = new ArrayList<>();
        userTypeRepository.findAll().forEach(userType -> resultList.add(userTypeMapper.toDto(userType)));
        return resultList;
    }


    public UserTypeDto findById(Long id) {
        UserTypeDto dto = userTypeMapper.toDto(userTypeRepository.findById(id).orElse(null));
        return dto;
    }

redis-cli caches

 1) "com.payment.data.domain.UserTypeTranslate"
 2) "redisson__execute_task_once_latch:{com.payment.data.domain.UserType}"
 3) "redisson-hibernate-timestamp"
 4) "com.payment.data.domain.UserType"
 5) "redisson__execute_task_once_latch:{com.payment.data.domain.UserTypeTranslate}"

Log
First request

2024-03-21 12:28:32.777  INFO [Payment,231920eac57ccff0dbe1ff94868725d2,1a14515245a5f932] user1 2743744 --- [nio-9101-exec-1] c.a.f.c.i.p.HeaderValidatorInterceptor   : HeaderValidatorInterceptor is running : HeaderValidatorInterceptor
2024-03-21 12:28:32.955 DEBUG [Payment,231920eac57ccff0dbe1ff94868725d2,1706a9885cf4b6b6] user1 2743744 --- [nio-9101-exec-1] o.h.SQL                                  : select ut1_0.id,ut1_0.code,ut1_0.createdate,ut1_0.createuser,ut1_0.updatedate,ut1_0.updateuser,ut1_0.versionid from usertype ut1_0 where ut1_0.id in (?)
2024-03-21 12:28:32.972 TRACE [Payment,231920eac57ccff0dbe1ff94868725d2,1706a9885cf4b6b6] user1 2743744 --- [nio-9101-exec-1] o.h.o.j.bind                             : binding parameter (1:BIGINT) <- [61036]
2024-03-21 12:28:33.081 DEBUG [Payment,231920eac57ccff0dbe1ff94868725d2,640290cfa62e8823] user1 2743744 --- [nio-9101-exec-1] o.h.SQL                                  : select utt1_0.id,utt1_0.createdate,utt1_0.createuser,utt1_0.description,utt1_0.langcode,utt1_0.name,utt1_0.updatedate,utt1_0.updateuser,utt1_0.usertypeid,utt1_0.versionid from usertypetranslate utt1_0 where utt1_0.usertypeid=? and utt1_0.langcode=?
2024-03-21 12:28:33.081 TRACE [Payment,231920eac57ccff0dbe1ff94868725d2,640290cfa62e8823] user1 2743744 --- [nio-9101-exec-1] o.h.o.j.bind                             : binding parameter (1:BIGINT) <- [61036]
2024-03-21 12:28:33.081 TRACE [Payment,231920eac57ccff0dbe1ff94868725d2,640290cfa62e8823] user1 2743744 --- [nio-9101-exec-1] o.h.o.j.bind                             : binding parameter (2:VARCHAR) <- [tr]
2024-03-21 12:28:33.123 DEBUG [Payment,231920eac57ccff0dbe1ff94868725d2,640290cfa62e8823] user1 2743744 --- [nio-9101-exec-1] o.h.c.s.s.AbstractReadWriteAccess        : Caching data from load [region=`com.payment.data.domain.UserTypeTranslate` (AccessType[read-write])] : key[com.payment.data.domain.UserTypeTranslate#53813] -> value[CacheEntry(com.payment.data.domain.UserTypeTranslate)]
2024-03-21 12:28:33.224 DEBUG [Payment,231920eac57ccff0dbe1ff94868725d2,640290cfa62e8823] user1 2743744 --- [nio-9101-exec-1] o.h.c.s.s.AbstractReadWriteAccess        : Checking writeability of read-write cache item [timestamp=`7008291308015616`, version=`0`] : txTimestamp=`7008310529507328`, newVersion=`0`
2024-03-21 12:28:33.224 DEBUG [Payment,231920eac57ccff0dbe1ff94868725d2,640290cfa62e8823] user1 2743744 --- [nio-9101-exec-1] o.h.c.s.s.AbstractReadWriteAccess        : Cache put-from-load [region=`AccessType[read-write]` (com.payment.data.domain.UserTypeTranslate), key=`com.payment.data.domain.UserTypeTranslate#53813`, value=`CacheEntry(com.payment.data.domain.UserTypeTranslate)`] failed due to being non-writable

Second request

2024-03-21 12:28:51.111  INFO [Payment,38f2560f55dd64f08dd34dd1b462c76f,1b75b51a041fd34e] user1 2743744 --- [nio-9101-exec-2] c.a.f.c.i.p.HeaderValidatorInterceptor   : HeaderValidatorInterceptor is running : HeaderValidatorInterceptor
2024-03-21 12:28:51.188 DEBUG [Payment,38f2560f55dd64f08dd34dd1b462c76f,e7502958f28a7ef3] user1 2743744 --- [nio-9101-exec-2] o.h.SQL                                  : select ut1_0.id,ut1_0.code,ut1_0.createdate,ut1_0.createuser,ut1_0.updatedate,ut1_0.updateuser,ut1_0.versionid from usertype ut1_0 where ut1_0.id in (?)
2024-03-21 12:28:51.189 TRACE [Payment,38f2560f55dd64f08dd34dd1b462c76f,e7502958f28a7ef3] user1 2743744 --- [nio-9101-exec-2] o.h.o.j.bind                             : binding parameter (1:BIGINT) <- [61036]
2024-03-21 12:28:51.266 DEBUG [Payment,38f2560f55dd64f08dd34dd1b462c76f,063a1bbbe2301ef6] user1 2743744 --- [nio-9101-exec-2] o.h.SQL                                  : select utt1_0.id,utt1_0.createdate,utt1_0.createuser,utt1_0.description,utt1_0.langcode,utt1_0.name,utt1_0.updatedate,utt1_0.updateuser,utt1_0.usertypeid,utt1_0.versionid from usertypetranslate utt1_0 where utt1_0.usertypeid=? and utt1_0.langcode=?
2024-03-21 12:28:51.266 TRACE [Payment,38f2560f55dd64f08dd34dd1b462c76f,063a1bbbe2301ef6] user1 2743744 --- [nio-9101-exec-2] o.h.o.j.bind                             : binding parameter (1:BIGINT) <- [61036]
2024-03-21 12:28:51.266 TRACE [Payment,38f2560f55dd64f08dd34dd1b462c76f,063a1bbbe2301ef6] user1 2743744 --- [nio-9101-exec-2] o.h.o.j.bind                             : binding parameter (2:VARCHAR) <- [tr]
2024-03-21 12:28:51.305 DEBUG [Payment,38f2560f55dd64f08dd34dd1b462c76f,063a1bbbe2301ef6] user1 2743744 --- [nio-9101-exec-2] o.h.c.s.s.AbstractReadWriteAccess        : Caching data from load [region=`com.payment.data.domain.UserTypeTranslate` (AccessType[read-write])] : key[com.payment.data.domain.UserTypeTranslate#53813] -> value[CacheEntry(com.payment.data.domain.UserTypeTranslate)]
2024-03-21 12:28:51.322 DEBUG [Payment,38f2560f55dd64f08dd34dd1b462c76f,063a1bbbe2301ef6] user1 2743744 --- [nio-9101-exec-2] o.h.c.s.s.AbstractReadWriteAccess        : Checking writeability of read-write cache item [timestamp=`7008291308015616`, version=`0`] : txTimestamp=`7008310604443648`, newVersion=`0`
2024-03-21 12:28:51.322 DEBUG [Payment,38f2560f55dd64f08dd34dd1b462c76f,063a1bbbe2301ef6] user1 2743744 --- [nio-9101-exec-2] o.h.c.s.s.AbstractReadWriteAccess        : Cache put-from-load [region=`AccessType[read-write]` (com.payment.data.domain.UserTypeTranslate), key=`com.payment.data.domain.UserTypeTranslate#53813`, value=`CacheEntry(com.payment.data.domain.UserTypeTranslate)`] failed due to being non-writable

From the limited logs you shared I can’t really deduce why the second time the cache is not getting hit. There are a lot of things at play in these examples that you posted here.

My first suggestion would be to try and simplify as much as possible to understand where is the cause of the problem. Try reproducing this behavior without Spring, e.g. using our simplified test case templates, and you can share with us what you find.

For queries, you will have to enable query caching on that query with Query.setHint("org.hibernate.cacheable", true). I don’t know how to enable that for Spring Data. Ask the Spring community about that.