Skip to content
Advertisement

Should I specify key-type and value-type when using ECache in Spring Boot?

I’ve seen a lot of articles where those parameters where specified, like that:

    <cache alias="dishDTOs" uses-template="default">
    <key-type>java.lang.Integer</key-type>
    <value-type>com.topjava.graduation.restaurant.dto.DishResponseDTO</value-type>
</cache>

But what is the point of it? Everything seems to work even without them, moreover, if i specify these I have this exception

Invalid value type, expected : com.topjava.graduation.restaurant.dto.DishResponseDTO but was : java.util.ArrayList

Methods under test ( just call these 2 one by one ):

        @Cacheable(value = "dishDTOs", key = "-2")
    public List<DishResponseDTO> getAll() {
    // code
}
    @Cacheable(value = "dishDTOs", key = "#dishId")
    public DishResponseDTO getOne(int dishId) {
    // code

}

Advertisement

Answer

You should probably use two different caches. In the first case, you are trying to save a list (return type of the getAll method) into a cache specified for individual DishResponseDTOs. That’s why you get the exception.

If you don’t specify the types, the cache will assume Object, so you won’t have any type safety. See, for example, Ehcache docs.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement