Templates by BIGtheme NET

Cassandra UDTs Java Example

In this Article, I will show How to create an UDTs (User Data types)
in Cassandra. How to map these UDTs to Java beans. How to do some
basic operations like insert, update, delete using Java.

Tools Uses :

1) Apache-cassandra-2.1.6
2) eclipse version Luna 4.4.1.
3) Maven 4.0.0
4) JDK 1.7

UDTs (User Data types) are common in many projects.
We can create or define project specific data types in database.

Cassandra supports the UDTs.

Simple use case :

Orders is one entity having customer as property.

1

Here customer is a Cassandra user defined data type.

Simple steps to create UDTs :

1) Create a KEYSPACE, If not existed:

// Here devjavasource is the key space name.
CREATE KEYSPACE devjavasource WITH replication = 
{'class': 'SimpleStrategy', 'replication_factor': '1'};

2) Create customer User Data Type :

// Here customer is UDT name
CREATE TYPE devjavasource.customer (
    id text,
	name text,
	coupon_code text,
	address text
);

UDT

3) Create table orders that is having customer UDT as one
of the column:

// Here orders is a table
CREATE TABLE devjavasource.orders(
	order_id text, 
	item_id text, 
	no_of_items int, 
	customer frozen, // customer is a UDT
	PRIMARY KEY (order_id, item_id)
);

create_orders

4) insert some data into orders table :

INSERT INTO orders(order_id, item_id , no_of_items, customer ) values 
('order_101', 'item_12', 2,{id: 'CUST_ID_1', name: 'Peater', 
coupon_code: 'Coupon_Code_10245', address:'2 Lane, 13th Street, Oakland, CA'});

insert_data

3) Write a simple program to retrieve data from UDT :

1) Create a maven project.

2) Add required dependencies.

3) Create a simple java program to retrieve data.

4) Start cassandra server.

5) Run and verify the out put.

Add required dependencies :

Open pom.xml file and add given dependency.

<dependency>
	<groupId>com.datastax.cassandra</groupId>
	<artifactId>cassandra-driver-mapping</artifactId>
	<version>2.1.2</version>
</dependency> 

Create a simple java program to retrieve data :

Create a Customer class and map this class to UDT (customer).
@UDT – is the annotation that map Customer class to customer UDT.

@UDT(name = "customer", keyspace = "devjavasource")

Define all properties of the Customer class and map each property
to customer UDT property.

@Field – is the annotation that map Customer class properties
to customer UDT properties.

// Here coupon_code is customer UDT property
// and couponCode is Customer class property.
@Field(name = "coupon_code")
private String couponCode;

Always you should define setter and getters to all the properties
of the Customer class.

Complete Customer class source code is Here,
Customer.java

package com.devjavasource.cassandra.CassandraDbService;

import com.datastax.driver.mapping.annotations.UDT;
import com.datastax.driver.mapping.annotations.Field;

@UDT(name = "customer", keyspace = "devjavasource")
public class Customer {
	@Field(name = "id")
	private String id;

	@Field(name = "name")
	private String name;

	@Field(name = "coupon_code")
	private String couponCode;

	@Field(name = "address")
	private String address;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCouponCode() {
		return couponCode;
	}

	public void setCouponCode(String couponCode) {
		this.couponCode = couponCode;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Customer{" + "id='" + id + '\'' + "name='" + name + '\''
				+ ", couponCode=" + couponCode + ", address=" + address + "} "
				+ super.toString();
	}
}

Create a Simple class App.java to retrieve the data,

Create a Cluster object and session objects,

Cluster cluster = null;
Session session = null;
cluster = Cluster.builder().withProtocolVersion(ProtocolVersion.V3)
          .addContactPoint("localhost").build();
session = cluster.connect("devjavasource");

Create a mapper to map Customer class to customer UDT,

UDTMapper<Customer> mapper = new MappingManager(session).udtMapper(Customer.class);

Here UDTMapper is class, that maps a particular class
to a UDT.

Complete source code is Here,
App.java

package com.devjavasource.cassandra.CassandraDbService;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.UDTValue;
import com.datastax.driver.mapping.MappingManager;
import com.datastax.driver.mapping.UDTMapper;

public class App {
	public static void main(String[] args) {

		Cluster cluster = null;
		Session session = null;

		try {
			cluster = Cluster.builder().withProtocolVersion(ProtocolVersion.V3)
					.addContactPoint("localhost").build();
			session = cluster.connect("devjavasource");

			UDTMapper<Customer> mapper = new MappingManager(session)
                                                           .udtMapper(Customer.class);

			ResultSet execute = session.execute("select * from orders");

			for (Row row : execute) {
				UDTValue customer = row.getUDTValue("customer");
				System.out.println(customer);
				System.out.println(mapper.fromUDT(customer));
			}

		} catch (Exception exp) {
			exp.printStackTrace();
		} finally {
			cluster.close();
		}
	}
}

4) Start the Cassandra server :

Cassandra server should be up and running.
If the server is not running, run the server using following command.

Command to start Casandra server is,
C:\apache-cassandra-2.1.6\bin>cassandra.bat -f

5) Run Maven project :

Select and Run As -> Java Application.

Out Put :

{id:'CUST_ID_1', name:'Peater', coupon_code:'Coupon_Code_10245', address:'2 Lane, 13th Street, Oakland, CA'}
Customer{id='CUST_ID_1'name='Peater', couponCode=Coupon_Code_10245, address=2 Lane, 13th Street, Oakland, CA} com.devjavasource.cassandra.CassandraDbService.Customer@6fb117f0

You can download complete project, Here

CassandraDbService

*** Venkat – Happy leaning ****