spring-data-redis icon indicating copy to clipboard operation
spring-data-redis copied to clipboard

Callbacks are not parameterized fully [DATAREDIS-235]

Open spring-projects-issues opened this issue 12 years ago • 4 comments
trafficstars

William Hoyle opened DATAREDIS-235 and commented

Template callbacks, for example SessionCallback, only have return type parameters. This leads to some unnecessary casts. Also, the callback methods have type parameters with names that shadow the template parameter names.

Consider:

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.hash.HashMapper;

/**
 * Utility for transactionally mapping objects to/from hashes.
 */

public class Hasher<T, K, V, HK, HV> {
    private RedisTemplate<K, V> template;
    private HashMapper<T, HK, HV> mapper;

    public Hasher(RedisTemplate<K, V> template, HashMapper<T, HK, HV> mapper) {
        this.template = template;
        this.mapper = mapper;
    }

    public T get(K key) {
        HashOperations<K, HK, HV> hashOps = template.opsForHash();
        return mapper.fromHash(hashOps.entries(key));
    }

    public void put(final K key, final T value) {

        //
        // Clear hash and set in a transaction
        //

        template.execute(new SessionCallback<Void>() {
            @Override
            public <K, V> Void execute(RedisOperations<K, V> ops) throws DataAccessException {
                ops.multi();
                // Clear all values.
                // Need to cast because SessionCallback is not <T, K, V>.
                ops.delete((K) key); // execute<K> shadows Hasher<K>
                HashOperations<K, HK, HV> hashOps = ops.opsForHash();
                // Put all values.
                // Need to cast again.
                hashOps.putAll((K) key, mapper.toHash(value)); // cast again
                ops.exec();
                return null;
            }
        });
    }
}

1 votes, 2 watchers

spring-projects-issues avatar Aug 19 '13 02:08 spring-projects-issues

Markus Heiden commented

The type parameters K and V should be at type level, not a method level. Otherwise it is not possible to use SessionCallback as a lambda. RedisTemplate#execute should look like: public <T> T execute(SessionCallback<K, V, T> session) { ... } This way type safety is ensured.

spring-projects-issues avatar May 14 '16 22:05 spring-projects-issues

No one assigned

TowardsTheSunSun avatar Dec 14 '21 02:12 TowardsTheSunSun

2023.....

HongJian-Yang avatar Dec 14 '23 10:12 HongJian-Yang