有人可以帮助我使用Java以格式yyyy-mm-dd
将当前系统日期存储在cassandra日期列中吗?使用java.sql.Date
保存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
) ;
答案 0 :(得分:1)
将rece
的数据类型声明为com.datastax.driver.core.LocalDate
或编写自定义编解码器以编码java.sql.Date
并将其注册到群集。
自定义编解码器示例:
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);
}
答案 1 :(得分:0)
我遇到了类似的问题,根据Ashraful的回答,我在模型中添加了以下代码来解决该问题。
Meta Data Model:
public class MetaData {
private String receive_date;
private String receive_hour;
**private com.datastax.driver.core.LocalDate error_date;**
}
In my service class, added below code.
final MetaData metaData = MetaData.builder()
.receive_date(row.getString("receive_date"))
.receive_hour(row.getString("receive_hour"))
.error_date(row.getDate("error_date"))
.build();