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.D
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.
Custom codec Example :
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();
}
}
How to use it ?
Example :
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);
}
I had similar issues and As per Ashraful's answer, I have added below code in my model which resolved the issue.
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();