具有下表
"CREATE TABLE IF NOT EXISTS user_preferences (" +
" user_id text," +
" my_duration duration," +
" last_modified timestamp," +
" primary key((id))" +
");";
当尝试保留以下模型时
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import java.time.Duration;
@Table(name = "user_preferences")
public class UserPreferences {
@PartitionKey
@Column(name = "user_id")
private String userId;
@Column(name = "my_duration")
private Duration myDuration;
@Column(name = "last_modified")
private Date lastModified;
}
我得到此编解码器未找到的异常。
com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [duration <-> java.time.Duration]
at com.datastax.driver.core.exceptions.CodecNotFoundException.copy(CodecNotFoundException.java:57) ~[cassandra-driver-core-3.6.0.jar:na]
at com.datastax.driver.core.exceptions.CodecNotFoundException.copy(CodecNotFoundException.java:25) ~[cassandra-driver-core-3.6.0.jar:na]
at com.datastax.driver.mapping.DriverThrowables.propagateCause(DriverThrowables.java:39) ~[cassandra-driver-mapping-3.6.0.jar:na]
at com.datastax.driver.mapping.Mapper.save(Mapper.java:356) ~[cassandra-driver-mapping-3.6.0.jar:na]
注意:读取工作正常,可能是因为尚未填充表格。
Datastax-core 3.3.2是否支持java.time.Duration?
答案 0 :(得分:1)
评论的补充: 默认编解码器返回com.datastax.driver.core.Duration! C *持续时间与java.time.Duration不兼容。因此,您应该在代码中使用驱动程序Duration类型,或者提供自己的编解码器。
这个特定问题的答案有误,但如果您想实现自己的编解码器仍然很有用,则必须以这种方式进行注册。
对于其他java.time类,您需要使用/注册额外的jdk8编解码器: https://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/extras/
import com.datastax.driver.extras.codecs.jdk8.InstantCodec;
import java.time.Instant;
cluster.getConfiguration().getCodecRegistry()
.register(InstantCodec.instance);
或者如果您无权访问群集对象
com.datastax.driver.core.CodecRegistry.DEFAULT_INSTANCE.register(InstantCodec.instance);