Cassandra CodecNotFoundException:找不到请求的操作的编解码器

问题描述 投票:1回答:2

我有一个枚举字段,我想映射到cassandra中的列

public enum MyEnum {
    Aa,
    Bb,
    Cc,
}

这是我如何注册它

CodecRegistry myCodecRegistry = new CodecRegistry();
             myCodecRegistry.register(new EnumOrdinalCodec<MyEnum>(MyEnum.class));

            cluster = Cluster.builder().addContactPoint(cassandraHosts).withPort(cassandraPort).withCodecRegistry(myCodecRegistry).build();

我能够连接到cassandra就好了。这是模型类的片段

public class MyModel
{
    @PartitionKey
    @Column(name="id")
    private String id;

    @ClusteringColumn
    @Column(name="name")
    private String name = "";

    @Column(name="enum")
    private MyEnum enum;

    public MyModel(String i, String n)
    {
        id=i;
        name=n
        enum=MyEnum.Aa;
    }
}

这是我如何使用CQL创建表

CREATE TABLE IF NOT EXISTS 
tab 
    (
        name varchar ,
        id varchar, 
        enum varchar, 
        PRIMARY KEY ((id), name));

最后,我有我的映射代码

    manager = new MappingManager(session);
    mapper = manager.mapper(MyModel.class);
    accessor = manager.createAccessor(MyAccessor.class);

这是MyAccessor

@Accessor
public interface MyAccessor{

    @Query("SELECT * FROM case WHERE id=? and name=? ALLOW FILTERING;")
    MyModel readByIdAndName(String id,String name);
}

所以当我尝试执行

MyModel m = new MyModel("asdasf","qw");
mapper.save(m);

我明白了

com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [varchar <-> my.pack.MyEnum]
    at com.datastax.driver.core.exceptions.CodecNotFoundException.copy(CodecNotFoundException.java:56)
    at com.datastax.driver.core.exceptions.CodecNotFoundException.copy(CodecNotFoundException.java:25)
    at com.datastax.driver.mapping.DriverThrowables.propagateCause(DriverThrowables.java:41)
    at com.datastax.driver.mapping.Mapper.save(Mapper.java:289)

我究竟做错了什么?

java cassandra datastax cassandra-3.0
2个回答
3
投票

EnumOrdinalCodec仅用于在int < - > Enum之间进行映射。由于您的Enum基于字符串,因此请使用EnumNameCodec类。这两个编解码器类的Javadoc如下所示。希望能帮助到你。

EnumNameCodec

将Enum实例序列化为CQL varchars的编解码器,表示由Enum.name()返回的程序名。

EnumOrdinalCodec

将Enum实例序列化为CQL整数的编解码器,表示由Enum.ordinal()返回的序数值。

链接到Javadoc


0
投票

更改代码如下:

/* This is not required
CodecRegistry myCodecRegistry = new CodecRegistry();
         myCodecRegistry.register(new EnumOrdinalCodec<MyEnum>(MyEnum.class));
*/
cluster = Cluster
    .builder()
    .addContactPoint(cassandraHosts)
    .withPort(cassandraPort)
    .build();

class MyEnumCodec: EnumOrdinalCodec<MyEnum> { MyEnumCodec() { super(MyEnum.class) } }

public class MyModel
{
    @PartitionKey
    @Column(name="id")
    private String id;

    @ClusteringColumn
    @Column(name="name")
    private String name = "";

    @Column(name="enum", codec = MyEnumCodec.class)
    private MyEnum enum;

    public MyModel(String i, String n)
    {
        id=i;
        name=n
        enum=MyEnum.Aa;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.