Skip to content

Callbacks are not parameterized fully [DATAREDIS-235] #815

Open
@spring-projects-issues

Description

@spring-projects-issues

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions