K. *_*ddy 5 java spring cassandra spring-boot spring-data-cassandra
我有一个带有日期类型列的cassandra表,如下所示:
create table people
(
id int primary key,
name text,
email text,
dob date
);
Run Code Online (Sandbox Code Playgroud)
我正在使用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>{
}
Run Code Online (Sandbox Code Playgroud)
我按如下方式插入新人:
personRepository.save(new Person(1, "Siva","siva@gmail.com", new java.util.Date()));
Run Code Online (Sandbox Code Playgroud)
它抛出以下错误:
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]
Run Code Online (Sandbox Code Playgroud)
但是,如果我将dob列类型设置为时间戳,那么它工作正常.是否可以使用日期类型列并使用java.util.Date类型属性?
Ps:即使我使用java.sql.Date我也得到同样的错误.
Ash*_*lam 11
使用 com.datastax.driver.core.LocalDate
您可以使用这些方法来获得LocalDate
从java.util.Date
或者您可以创建自己的编解码器,以允许您插入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();
}
}
Run Code Online (Sandbox Code Playgroud)
创建连接时,您必须注册:
CodecRegistry codecRegistry = new CodecRegistry();
codecRegistry.register(new DateCodec(TypeCodec.date(), Date.class));
Cluster.builder().withCodecRegistry(codecRegistry).build();
Run Code Online (Sandbox Code Playgroud)
更多信息:http://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/
归档时间: |
|
查看次数: |
9153 次 |
最近记录: |