找不到请求操作的编解码器:[duration< ->java.time.duration]

flseospp  于 2021-06-10  发布在  Cassandra
关注(0)|答案(1)|浏览(490)

有下表

"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?

zf9nrax1

zf9nrax11#

添加注解:默认编解码器返回com.datastax.driver.core.duration!c*duration与java.time.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);

相关问题