本文介绍了如何使用映射管理器将 java.sql.Date 存储在 cassandra 日期字段中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮助我使用 Java 将当前系统日期以 yyyy-mm-dd
格式存储在 cassandra 日期列中吗?使用 MappingManager
保存 java.sql.Date
时出现异常.
Can someone help me to store the current system date in cassandra date column in format yyyy-mm-dd
using Java? I get exception while saving the java.sql.Date
using MappingManager
.
我的示例程序是:
Test.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.Date
进行编码并将其注册到集群.
Either declare data type of rece
to com.datastax.driver.core.LocalDate
or Write a custom codec to encode java.sql.Date
and register it to the cluster.
自定义编解码器示例:
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.sql.Date 存储在 cassandra 日期字段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!