gpt4 book ai didi

spring - 使用 spring-data-cassandra 的用户定义类型

转载 作者:行者123 更新时间:2023-12-04 16:27:01 25 4
gpt4 key购买 nike

我希望创建如下模型,如何在 spring-data-cassandra 中使用用户定义的类型?

{
email: "test@example.com",
name: {
fname: "First",
lname: "Last"
}
}

最佳答案

Spring Data Cassandra 现在支持用户定义的数据类型。最新版本 1.5.0.RELEASE 使用 Cassandra Data stax 驱动程序 3.1.3,因此它现在可以工作。请按照以下步骤使其工作

如何在 Spring Data Cassandra 中使用 UserDefinedType(UDT) 特性:

  • 我们需要使用最新的Spring data Cassandra jar (1.5.0.RELEASE)

    组:'org.springframework.data',名称:'spring-data-cassandra',版本:'1.5.0.RELEASE'
  • 确保它使用以下版本的 jar :

    datastax.cassandra.driver.version=3.1.3
    spring.data.cassandra.version=1.5.0.RELEASE
    spring.data.commons.version=1.13.0.RELEASE
    spring.cql.version=1.5.0.RELEASE
  • 在 Cassandra 中创建用户定义类型:类型名称应与 POJO 类中定义的相同

  • 地址数据类型
    CREATE TYPE address_type ( 
    id text,
    address_type text,
    first_name text,
    phone text
    );
  • 在 Cassandra 中使用其中一列作为 UDT 创建列族:

  • 员工表:
    CREATE TABLE employee( 
    employee_id uuid,
    employee_name text,
    address frozen,
    primary key (employee_id, employee_name)
    );
  • 在域类中,定义带有注释的字段 -CassandraType 和 DataType 应为 UDT:
    @Table("employee") 
    public class Employee {
    -- othere fields--
    @CassandraType(type = DataType.Name.UDT, userTypeName = "address_type")
    private Address address;
    }
  • 为用户定义类型创建域类:我们需要确保用户定义类型模式中的列名必须与域类中的字段名相同。
    @UserDefinedType("address_type") 
    public class Address {
    @CassandraType(type = DataType.Name.TEXT)
    private String id;
    @CassandraType(type = DataType.Name.TEXT)
    private String address_type;
    }
  • 在 Cassandra 配置中,更改此项:
    @Bean public CassandraMappingContext mappingContext() throws Exception { 
    BasicCassandraMappingContext mappingContext = new BasicCassandraMappingContext();
    mappingContext.setUserTypeResolver(new
    SimpleUserTypeResolver(cluster().getObject(), cassandraKeyspace));
    return mappingContext;
    }
  • 用户定义的类型应该在所有地方都具有相同的名称。例如
    @UserDefinedType("address_type")
    @CassandraType(type = DataType.Name.UDT, userTypeName = "address_type")
    CREATE TYPE address_type
  • 关于spring - 使用 spring-data-cassandra 的用户定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862460/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com