2017-12-27 494 views
0

我有我想要映射到一列卡桑德拉卡桑德拉CodecNotFoundException:編解碼器找不到請求的操作

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) 

我到底做錯了什麼?

回答

3

EnumOrdinalCodec用於在int < - > Enum only之間映射。由於您的Enum基於字符串,因此請使用EnumNameCodec類。這兩個編解碼器類的Javadoc如下所示。希望能幫助到你。

EnumNameCodec

甲序列化枚舉實例作爲CQL VARCHAR處理表示由Enum.name作爲返回 其程序名稱編解碼器()。

EnumOrdinalCodec

序列化枚舉實例作爲表示由Enum.ordinal作爲返回其 序號值CQL整數A編碼解碼法()。

鏈接Javadoc

+0

謝謝!不能相信我錯過了:) – AbtPst