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

时间:2017-03-28 08:15:15

标签: java spring spring-boot cassandra spring-data-cassandra

我有一个带有日期类型列的cassandra表,如下所示:

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

我正在使用SpringBoot 1.5.2 + Spring Data Cassandra Starter。

@Table("people")
public class Person {
    @PrimaryKey
    Integer id;
    private String name;
    private String email;
    private java.util.Date dob;
    //setters and getters
}

public interface PersonRepository extends CrudRepository<Person, Integer>{

}

我按如下方式插入新人:

personRepository.save(new Person(1, "Siva","siva@gmail.com", new java.util.Date()));

抛出以下错误:

Caused by: com.datastax.driver.core.exceptions.InvalidQueryException: Expected 4 byte long for date (8)
    at com.datastax.driver.core.Responses$Error.asException(Responses.java:136) ~[cassandra-driver-core-3.1.4.jar:na]
    at com.datastax.driver.core.DefaultResultSetFuture.onSet(DefaultResultSetFuture.java:179) ~[cassandra-driver-core-3.1.4.jar:na]
    at com.datastax.driver.core.RequestHandler.setFinalResult(RequestHandler.java:177) ~[cassandra-driver-core-3.1.4.jar:na]
    at com.datastax.driver.core.RequestHandler.access$2500(RequestHandler.java:46) ~[cassandra-driver-core-3.1.4.jar:na]

但如果我将 dob 列类型设为时间戳,那么它运行正常。是否可以使用日期类型列并使用 java.util.Date 类型属性?

P.s:即使我使用java.sql.Date,我也会遇到同样的错误。

1 个答案:

答案 0 :(得分:9)

使用com.datastax.driver.core.LocalDate

您可以使用以下任何一种方法从LocalDate

获取java.util.Date
  • LocalDate.fromYearMonthDay(2017,03,28)
  • LocalDate.fromMillisSinceEpoch(new Date()。getTime())

或者您可以创建自己的编解码器,以便将java.util.Date插入到Cassandra日期类型中。

你可以从下面开始:

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

}

创建连接时,您必须注册:

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

更多信息:http://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/