User Defined Type with spring-data-cassandra

User Defined data type is now supported by Spring Data Cassandra. The latest release 1.5.0.RELEASE uses Cassandra Data stax driver 3.1.3 and hence its working now. Follow the below steps to make it working

How to use UserDefinedType(UDT) feature with Spring Data Cassandra :

  1. We need to use the latest jar of Spring data Cassandra (1.5.0.RELEASE)

    group: ‘org.springframework.data’, name: ‘spring-data-cassandra’, version: ‘1.5.0.RELEASE’

  2. Make sure it uses below versions of the 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

  3. Create user defined type in Cassandra : The type name should be same as defined in the POJO class

Address data type

CREATE TYPE address_type ( 
    id text, 
    address_type text, 
    first_name text, 
    phone text 
);
  1. Create column-family with one of the columns as UDT in Cassandra:

Employee table:

CREATE TABLE employee( 
   employee_id uuid, 
   employee_name text, 
   address frozen, 
   primary key (employee_id, employee_name) 
);
  1. In the domain class, define the field with annotation -CassandraType and DataType should be UDT:

    @Table("employee") 
    public class Employee { 
       -- othere fields-- 
       @CassandraType(type = DataType.Name.UDT, userTypeName = "address_type") 
       private Address address; 
    }
    
  2. Create domain class for the user defined type : We need to make sure that column name in the user defined type schema has to be same as field name in the domain class.

    @UserDefinedType("address_type") 
    public class Address { 
        @CassandraType(type = DataType.Name.TEXT) 
        private String id; 
        @CassandraType(type = DataType.Name.TEXT) 
        private String address_type; 
    }
    
  3. In the Cassandra Config, Change this :

    @Bean public CassandraMappingContext mappingContext() throws Exception { 
        BasicCassandraMappingContext mappingContext = new BasicCassandraMappingContext(); 
        mappingContext.setUserTypeResolver(new 
        SimpleUserTypeResolver(cluster().getObject(), cassandraKeyspace)); 
        return mappingContext; 
    }
    
  4. User defined type should have the same name across everywhere. for e.g

    @UserDefinedType("address_type")
    @CassandraType(type = DataType.Name.UDT, userTypeName = "address_type")
    CREATE TYPE address_type
    

Leave a Comment