Search code examples
javaehcachespring-cache

Modifying the object changes the Ehcache value


    @Override
    @Cacheable(value = "user-cache", key = "#login", unless = "#result == null")
    public User findUserByLogin(final String login)
    {
        return em.find(User.class, login);
    }

If i set the password to null for example like below. What i saw the cache value is also modified accordingly because in the next call the cache is hit and the password there is set to NULL. Is this the right behavior? Do i have to create a new object after every retrieval if i want to modify that object.I am talking modifying in regard to not changing in the database but on service level.

    public User getUserByLogin(final String login)
{
    final User user = userRepository.findUserByLogin(login);
    user.setPassword(null);
    return user;
}

Solution

  • When using on-heap tier in Ehcache, keys and values are by reference. So any modification to the object will be reflected in the cache.