Java – How to retrieve Long (data type) values from the redis cache

How to retrieve Long (data type) values from the redis cache… here is a solution to the problem.

How to retrieve Long (data type) values from the redis cache

I store the userId as Long in the redis cache of my spring boot application, but return the Integer type and throw an exception when retrieving it

java.lang.Integer cannot be cast to java.lang.Long

Below is the code snippet I’m using.

@Cacheable(value = CacheConstants.GAUTH_CACHE, key = "#root.target.PASSWORD_SALT.concat(#loginTxt.toString())", unless = "#result == null")
    public Long getPasswordSaltFromLoginText(String loginTxt) {
        Long userId = null;
        if(StringUtils.isNotBlank(loginTxt)) {
            userId =  profileRepository.getUserIdForPasswordSalt(loginTxt, "PasswordSalt");
        }
        return userId;
    }

My Hibernate query is like this. where A.USR_ID type is Long

@Query(nativeQuery = true, value = "select A.USR_ID from user_tbl A, another_table B WHERE A.USR_ID = B.USR_ID AND "
            + " UPPER(A.loginTxt) = UPPER(:loginTxt) "
            + " AND B.prefName=:prefName ")

Long getUserId(@Param("loginTxt") String loginTxt, @Param("prefName") String prefName);

The entity class is

@Entity
@Table(name="Table1", schema = "Schema_name")
public class Profile {

@Id
    @Column(name="USR_Id")
    public Long USR_ID;

@Column(name="other_column")
    public Long other_column;

@Column(name="other_column2")
    public Long other_column2;

}

Solution

Redis caches do not support the Long data type. So I store the entire config file object into the redis cache and use getter(), and I was able to get the Long value.

@Query(nativeQuery = true, value = "select A.USR_ID,A.other_column,A.other_column2 from user_tbl A, another_table B WHERE A.USR_ID = B.USR_ID AND "
            + " UPPER(A.loginTxt) = UPPER(:loginTxt) "
            + " AND B.prefName=:prefName ")

Profile getUserId(@Param("loginTxt") String loginTxt, @Param("prefName") String prefName);

Related Problems and Solutions