How to store java.sql.Date in cassandra date field using mapping manager?

大憨熊 提交于 2019-12-01 01:09:28

Either declare data type of rece to com.datastax.driver.core.LocalDate or Write a custom codec to encode java.sql.Date and register it to the cluster.

Custom codec Example :

import com.datastax.driver.core.LocalDate;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.core.exceptions.InvalidTypeException;

import java.nio.ByteBuffer;
import java.sql.Date;


public class DateCodec extends TypeCodec<Date> {

    private final TypeCodec<LocalDate> innerCodec;

    public DateCodec(TypeCodec<LocalDate> codec, Class<Date> javaClass) {
        super(codec.getCqlType(), javaClass);
        innerCodec = codec;
    }

    @Override
    public ByteBuffer serialize(Date value, ProtocolVersion protocolVersion) throws InvalidTypeException {
        return innerCodec.serialize(LocalDate.fromMillisSinceEpoch(value.getTime()), protocolVersion);
    }

    @Override
    public Date deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
        return new Date(innerCodec.deserialize(bytes, protocolVersion).getMillisSinceEpoch());
    }

    @Override
    public Date parse(String value) throws InvalidTypeException {
        return new Date(innerCodec.parse(value).getMillisSinceEpoch());
    }

    @Override
    public String format(Date value) throws InvalidTypeException {
        return value.toString();
    }
}

How to use it ?

Example :

CodecRegistry codecRegistry = new CodecRegistry();
codecRegistry.register(new DateCodec(TypeCodec.date(), Date.class));

try (Cluster cluster = Cluster.builder().withCodecRegistry(codecRegistry).addContactPoint("127.0.0.1").withCredentials("cassandra", "cassandra").build(); Session session = cluster.connect("test")) {
    Mapper mapper = new MappingManager(session).mapper(Test.class);
    mapper.save(test);
}

I had similar issues and As per Ashraful's answer, I have added below code in my model which resolved the issue.

Meta Data Model:

public class MetaData {
private String receive_date;
private String receive_hour;
**private com.datastax.driver.core.LocalDate error_date;**
}

In my service class, added below code.
final MetaData metaData = MetaData.builder()
                    .receive_date(row.getString("receive_date"))
                    .receive_hour(row.getString("receive_hour"))
                    .error_date(row.getDate("error_date"))
                    .build();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!