有人可以帮助我使用 Java 将当前系统日期以 yyyy-mm-dd
格式存储在 cassandra 日期列中吗?使用 MappingManager
保存 java.sql.Date
时出现异常。
我的示例程序是:
测试.java
import com.datastax.driver.mapping.annotations.Table;
import java.sql.Date;
@Table(keyspace = "testing", name = "test")
public class Test {
private String uid;
private Date rece;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Date getRece() {
return rece;
}
public void setRece(Date rece) {
this.rece = rece;
}
}
TestDao.java
Mapper mapper = new MappingManager(session).mapper(Test.class);
mapper.save(test);
Cassandra 架构:
CREATE TABLE tokenizer.test (
id text PRIMARY KEY,
testdate date
) ;
最佳答案
将 rece
的数据类型声明为 com.datastax.driver.core.LocalDate
或编写自定义编解码器来编码 java.sql。日期
并将其注册到集群。
自定义编解码器示例:
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();
}
}
如何使用?
示例:
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);
}
关于java - 如何使用映射管理器将 java.sql.Date 存储在 cassandra 日期字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803848/