如何使用映射管理器在cassandra日期字段中存储java.sql.Date?
有人可以帮助我使用Java以yyyy-mm-dd
格式将当前系统日期存储在cassandra日期列中吗? 使用MappingManager
保存java.sql.Date
exception。
我的示例程序是:
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);
卡桑德拉图式:
CREATE TABLE tokenizer.test ( id text PRIMARY KEY, testdate date ) ;
将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 { private final TypeCodec innerCodec; public DateCodec(TypeCodec codec, Class 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.lang.NoClassDefFoundError中的exception
- .jfindClass中的错误(as.character(driverClass)):找不到类
- 为什么Cassandra客户端在没有epoll的情况下失败?
- 在cassandra中将json存储为文本vs blob的优缺点是什么?
- 考虑将序列化的java对象存储为cassandra作为JSON。 捕获量是多少?
- 使用Datastax Cassandra驱动程序时重用PreparedStatement?
- 使用hadoop运行jar时的NoSuchMethodError Sets.newConcurrentHashSet()
- Cassandra批量查询与单插入性能
- Apache Ignite – java.lang.ClassNotFoundException:未知对