首页 > 解决方案 > 如何在 Java 中使用 Cassandra Map 类型

问题描述

我已经在键空间中创建了表,例如

CREATE TABLE IF NOT EXISTS myks.users (user_id text, device_ids map<text,text>);

I'm trying to insert the below data using `spring-boot-starter-data-cassandra` library in Spring boot

{
    "userId" : "krishna",
    "deviceIds": {
        "DeviceId_0": "TYNLSANID7",
        "DeviceId_1": "julasjasd8",
        "DeviceId_2": "iu89074hasd",
        "DeviceId_3": "Lenovo hjyas|asdqnkasd"
    }
}

下面是实体类

@Column("user_id")
@CassandraType(type = DataType.Name.TEXT)
private String userId;

@Column("device_ids")
@CassandraType(type = DataType.Name.MAP)
private Map<String, String> deviceIds= new HashMap<>();

将数据插入表时出现以下异常

org.springframework.dao.InvalidDataAccessApiUsageException: Expected [2] type arguments for property ['deviceIds'] of type ['interface java.util.Map'] in entity [com.kri.entity.Users]; actual was [0]

标签: javaspring-bootcassandra

解决方案


文档中所述,当您使用 时,您应该typeArguments在注释定义中提供属性Collection,特别是对于Map数据类型,您应该提供两个DataType Name属性,一个用于键,一个用于值:

@CassandraType(type = DataType.Name.MAP,typeArguments = { DataType.Name.TEXT,DataType.Name.TEXT} 

推荐阅读