首页 文章

Cassandra Accessor / Mapper不映射udt字段

提问于
浏览
0

我正在使用datastax cassandra 3.1.2 . 我在cassandra中创建了下表并插入了一条记录 .

CREATE TYPE memory ( capacity text );
create TABLE laptop ( id uuid primary key, model text, ram frozen<memory> );
select * from laptop ;

 id                                   | model         | ram
--------------------------------------+---------------+-------------------
 e55cba2b-0847-40d5-ad56-ae97e793dc3e | Dell Latitude | {capacity: '8gb'}

当我尝试使用带有以下代码的Cassandra Accessor从Java中的冻结类型内存中获取容量字段时:

this.cluster = Cluster.builder().addContactPoint(node).withPort(port).build();
session = cluster.connect();
MappingManager manager = new MappingManager(session);
LaptopAccessor laptopAccessor = manager.createAccessor(LaptopAccessor.class);
Result<Laptop> cp = laptopAccessor.getOne(UUID.fromString("e55cba2b-0847-40d5-ad56-ae97e793dc3e"));
System.out.println(cp.one());

它给ram数据点本身是null .

id = null model = null ram = null

我期待映射器在映射和映射容量字段时创建ram实例并返回Laptop bean .

我有以下Accessor接口:

@Accessor
interface LaptopAccessor {
   @Query("SELECT ram.capacity FROM user_info.laptop where id=?")
   Result<Laptop> getOne(UUID id);
}

我有上面的表的以下java bean .

@Table(keyspace = "user_info", name = "laptop")
public class Laptop {

    private UUID id;
    private String model;
    private Memory ram;

    @PartitionKey
    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }


    public String getModel() {
        return model;
    }


    public void setModel(String model) {
        this.model = model;
    }

    @Frozen
    public Memory getRam() {
        return ram;
    }


    public void setRam(Memory ram) {
        this.ram = ram;
    }

    @Override
    public String toString() {
        return "id = " + id + " model = " + model + " ram = " + ram;
    }

}

@UDT(keyspace = "user_info", name = "memory")
public class Memory {

    private String capacity;

    @Field
    public String getCapacity() {
        return capacity;
    }


    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }

    @Override
    public String toString() {
        return "capacity = " + capacity ;
    }

}

当我更改查询以检索整个ram UDT时,代码工作正常 . 当我从查询中的udt中选择一些字段时,有人可以告诉我为什么映射器不起作用吗?

cassandra不支持这个吗?获取UDT字段的任何解决方法?

1 回答

  • 1

    我认为问题是访问者的返回类型:

    @Accessor
    interface LaptopAccessor {
       @Query("SELECT ram.capacity FROM user_info.laptop where id=?")
       Result<Laptop> getOne(UUID id);
    }
    

    由于您的查询仅选择 ram.capacity ,所有驱动程序返回的是一个行,其中一列为 String ,名称为 ram.capacity ,不会映射到 Laptop 中的任何字段 .

    相反,因为看起来你想要的只是匹配该查询的1行,你可以将 Accessor 更改为:

    @Accessor
    interface LaptopAccessor {
       @Query("SELECT ram.capacity FROM user_info.laptop where id=?")
       ResultSet getOne(UUID id);
    }
    

    访问者现在返回 ResultSet ,您可以调用 one().getString(0) 来获取容量 . 它's not ideal if you don'想直接处理 ResultSet ,但效果很好 .

    你不应该真的需要整个 Laptop 对象,因为你要求的是UDT的一个领域吗?

相关问题