I am looking to create models as below, how can I use user defined types in spring-data-cassandra?
{
email: "[email protected]",
name: {
fname: "First",
lname: "Last"
}
}
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 :
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'
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
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
);
Employee table:
CREATE TABLE employee(
employee_id uuid,
employee_name text,
address frozen,
primary key (employee_id, employee_name)
);
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;
}
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;
}
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;
}
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