How to insert java.util.Date values into Cassandra date type column using Spring Data Cassandra?

后端 未结 1 698
再見小時候
再見小時候 2020-12-19 12:33

I have cassandra table with a date type column as follows:

create table people
(
   id int primary key, 
   name text, 
   email text, 
   dob date
);


        
相关标签:
1条回答
  • 2020-12-19 13:19

    Use com.datastax.driver.core.LocalDate

    You can use any of these method to get LocalDate from java.util.Date

    • LocalDate.fromYearMonthDay(2017, 03, 28)
    • LocalDate.fromMillisSinceEpoch(new Date().getTime())

    Or you could create your own codec that will allow you to insert java.util.Date into Cassandra date type.

    You can start like the below one :

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

    When creating connectin you have to register :

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

    For more : http://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/

    0 讨论(0)
提交回复
热议问题