Cassandra Custom Collection Mapping

时间:2017-03-14 16:28:39

标签: collections cassandra datastax codec

我正在尝试创建一个将Java Map映射到Cassandra Set<UDTShift>的自定义编解码器。 UDTShift是用户定义的类型。下面是我的测试自定义编解码器类,根据说明:http://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/

我有UDTShift在cassandra数据库中称为“udt + shift”,并且在Java中也有ORM pojo类UDTShift类。

我在codecRegistry中注册此编解码器时遇到问题,我不确定这是否是创建编解码器的正确方法。

package com.sick.il.analytics.system.configuration.cassandracodec;

import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.core.UserType;
import com.datastax.driver.core.exceptions.InvalidTypeException;
import com.sick.il.analytics.system.configuration.model.UDTAssignedShift;

public class ShiftCodec extends TypeCodec < Map < String, Date[] >> {
    private final TypeCodec < Set < UDTAssignedShift >> innerCodec;

    private final UserType userType;
    public ShiftCodec(TypeCodec < Set < UDTAssignedShift >> innerCodec, Class < Map < String, Date[] >> javaClass) {
        super(innerCodec.getCqlType(), javaClass);
        this.innerCodec = innerCodec;
        this.userType = (UserType) innerCodec.getCqlType();
    }


    @Override
    public ByteBuffer serialize(Map < String, Date[] > value, ProtocolVersion protocolVersion)
    throws InvalidTypeException {

        return innerCodec.serialize(toCassandraSet(value), protocolVersion);
    }

    @Override
    public Map < String,
    Date[] > deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion)
    throws InvalidTypeException {
        // TODO Auto-generated method stub
        return toJavaMap(innerCodec.deserialize(bytes, protocolVersion));
    }

    @Override
    public Map < String,
    Date[] > parse(String value) throws InvalidTypeException {

        return value == null || value.isEmpty() || value.equals(null) ? null : toJavaMap(innerCodec.parse(value));
    }

    @Override
    public String format(Map < String, Date[] > value) throws InvalidTypeException {
        return value == null ? null : innerCodec.format(toCassandraSet(value));
    }


    protected Map < String,
    Date[] > toJavaMap(Set < UDTAssignedShift > shiftSets) {
        Date[] dates = new Date[6];
        Map < String, Date[] > map = new HashMap < > ();
        map.put("Monday", dates);
        return map;
    }
    protected Set < UDTAssignedShift > toCassandraSet(Map < String, Date[] > shiftMap) {
        Set < UDTAssignedShift > sets = new HashSet < > ();
        UDTAssignedShift shift = new UDTAssignedShift();
        shift.setShiftName("Monday_01");
        shift.setStartDate("15:30:00:000");
        shift.setEndDate("19:30:00:000");
        sets.add(shift);
        return sets;
    }

}

0 个答案:

没有答案