您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用Spring Data Cassandra将java.util.Date值插入Cassandra日期类型列中?

如何使用Spring Data Cassandra将java.util.Date值插入Cassandra日期类型列中?

您可以使用以下任何一种方法LocalDatejava.util.Date

或者,您可以创建自己的编解码器,以允许您将其插入java.util.DateCassandra日期类型。

您可以像下面这样开始:

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();
    }

}

创建connectin时,必须注册

CodecRegistry codecRegistry = new CodecRegistry();
codecRegistry.register(new DateCodec(TypeCodec.date(), Date.class));
Cluster.builder().withCodecRegistry(codecRegistry).build();

有关更多信息:http : //docs.datastax.com/zh-CN/developer/java- driver/3.1/manual/custom_codecs/

java 2022/1/1 18:21:13 有466人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶