在cassandra中使用UDT(用户定义类型)处理映射

时间:2018-03-09 16:52:05

标签: java generics spring-boot collections cassandra

假设我在Cassandra有一个产品表信息UDT

_sum

对于这些,我在 Java 中有两个类作为

Create table Product{
    id text,
    details map<text,<frozen<Information>>,
    detailsMore list<frozen<Information>>
}
Create Type Information{
    info1 text,
    info2 text
}

现在我使用CRUDRepository(spring)获取数据,现在我就像

@Table
Class Product{
String id;
Map<String, Information> details;
List<Information> details;
}
@UserDefinedType('Information')
Class Information{
String info1;
String info2;
}

现在这个prodObj包含像

这样的数据
Product prodObj = repo.find(id);

为什么用户定义的类型在列表的情况下转换为信息,但在Map的情况下它没有被转换?或者我做错了什么?。如果我直接尝试将此UDTValue of Map分配给Information,我会得到以下异常(显而易见)。     java.lang.ClassCastException:com.datastax.driver.core.UDTValue无法转换为信息

1 个答案:

答案 0 :(得分:0)

您需要为您的班级编写自定义编解码器,以便将UDTValue映射到您的Information班级。请参阅Java Driver documentation(我不想将其代码复制为插图)。

提供示例后更新:我不熟悉Spring Cassandra Mapper,但您可以直接使用Object Mapper from Java Driver获得相同的功能。您需要使用@UDT注释标记表示用户定义类型的类,并且驱动程序将负责它。我已经创建了工作示例 - 它可用here(请参阅output部分了解执行结果)。

相关问题