Templates by BIGtheme NET

Spring Data Cassandra : Retrieve Operation

In this Article, I will show How to retrieve single and bulk data from
Cassandra Database with Spring Data Cassandra Template.
How to create a maven project and add required dependencies.

Tools Uses :

1) spring-data-cassandra-1.2.1.RELEASE
2) Apache-cassandra-2.1.6
3) eclipse version Luna 4.4.1.
4) Maven 3.3.3
5) JDK 1.6

Steps to be follow :

1) Create a simple maven project.

2) Add the dependencies and

3) Write a simple program to retrieve data using Spring Cassandra Template.

4) Start the Cassandra server.

5) Run the program and verify the data in cassandra.

Add the given dependency to spring-data-cassandra API,


	org.springframework.data
	spring-data-cassandra
	1.2.1.RELEASE

Complete pom.xml file code is Here,
pom.xml


  4.0.0

  com.devjavasource.cassandra
  SpringDataCassandraExample
  0.0.1-SNAPSHOT
  jar

  SpringDataCassandraExample
  http://maven.apache.org

  
    UTF-8
  

  
    
      junit
      junit
      3.8.1
      test
    
    
	  com.datastax.cassandra
	  cassandra-driver-core
	  2.1.6
	
	
    
        org.springframework.data
        spring-data-cassandra
        1.2.1.RELEASE
    
  

Write a simple program to retrieve data using Spring Cassandra Template :

This program will do the following,

1) Create a Cluster object.

Cluster cluster = null;
cluster = Cluster.builder().addContactPoint("127.0.0.1").build();

A cluster object maintains a permanent connection to one of
the cluster nodes. builder() is a static method of Cluster class.

2) Create a session object

private static Session session;
session = cluster.connect("devjavasource");

Here “devjavasource” is the existed keyspace, I am using the same.
we can create a session object by passing key space name as parameter
to connect() method of cluster class.

3) Create CassandraOperations :

CassandraOperations is interface that helps to do Operations like select, insert, delete…etc
for interacting with Cassandra.

CassandraOperations cassandraOps = new CassandraTemplate(session);

Using select() method of CassandraTemplate class, we can select single
or multiple records from Cassandra Database.

// To select a single User information from Database
final String[] columns = new String[] { "id", "address", "name" };

Select select = QueryBuilder.select(columns).from("users");
select.where(QueryBuilder.eq("id", 11103));
final List<Users> results = cassandraOps
		.select(select, Users.class);

// Another way is, by using selectOneById() method
Users selectById = cassandraOps.selectOneById(Users.class, 11101);
			printList(Arrays.asList(selectById));		

// To select multiple User information at a time.
// Bulk select operation
Select allUserSelect = QueryBuilder.select(columns).from("users");
final List<Users> allUsers = cassandraOps.select(allUserSelect,
		Users.class);
		
final List<Users> allUsers1 = cassandraOps.select(
		"Select * from Users", Users.class);

Four different types of select() methods are available in
Spring Data CassandraTemplate,

// Execute query and convert ResultSet to the list of entities
<T> List<T> select(String cql, Class<T> type);
<T> List<T> select(Select select, Class<T> type);

<T> T selectOneById(Class<T> type, Object id);
<T> T selectOne(String cql, Class<T> type);

// Select the results Asynchronously
<T> Cancellable selectOneAsynchronously(Select select, Class<T> type, QueryForObjectListener<T> listener);
<T> Cancellable selectOneAsynchronously(String cql, Class<T> type, QueryForObjectListener<T> listener);
<T> Cancellable selectOneAsynchronously(Select select, Class<T> type, QueryForObjectListener<T> listener,
			QueryOptions options);
<T> Cancellable selectOneAsynchronously(String cql, Class<T> type, QueryForObjectListener<T> listener,
			QueryOptions options);

<T> T selectOne(Select select, Class<T> type);

// This is to find, whether object is exist in DB or not by given Id
boolean exists(Class<?> type, Object id);

// To get count of Objects
long count(Class<?> type);

What is QueryForObjectListener?

This is a Listener Interface, used to receive asynchronous results
expected as an object of specified type.

This Interface having two methods,

(a) onQueryComplete – This method will be called, upon completion.

(b) onException – Called if an exception is raised while getting or
converting the Result.

Complete Source code is Here,
App.java

package com.devjavasource.cassandra.SpringDataCassandraExample;

import java.util.Arrays;
import java.util.List;

import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.devjavasource.cassandra.dto.Users;

public class App {
	private static Cluster cluster;
	private static Session session;

	public static void main(String[] args) {

		try {

			cluster = Cluster.builder().addContactPoint("127.0.0.1").build();

			session = cluster.connect("devjavasource");

			CassandraOperations cassandraOps = new CassandraTemplate(session);

			System.out
					.println("Spring Data Cassandra Select Single User Example");
			System.out
					.println("=================================================");

			// To select a single User information from Database
			final String[] columns = new String[] { "id", "address", "name" };

			Select select = QueryBuilder.select(columns).from("users");
			select.where(QueryBuilder.eq("id", 11103));
			final List<Users> results = cassandraOps
					.select(select, Users.class);
			printList(results);

			System.out
					.println("\nSpring Data Cassandra bulk User Selection Example");
			System.out
					.println("====================================================");
			// To select multiple User information at a time.
			// Bulk select operation
			Select allUserSelect = QueryBuilder.select(columns).from("users");
			final List<Users> allUsers = cassandraOps.select(allUserSelect,
					Users.class);
			printList(allUsers);

			System.out
					.println("====================================================");
			final List<Users> allUsers1 = cassandraOps.select(
					"Select * from Users", Users.class);
			printList(allUsers1);

			System.out
					.println("====================================================");
			Users selectById = cassandraOps.selectOneById(Users.class, 11101);
			printList(Arrays.asList(selectById));

			// The below statement will give error, while using selectOne method
			// we have to ensure only Object is selected.
			// final Users User = cassandraOps.selectOne(allUserSelect,
			// Users.class);
			// printList(Arrays.asList(User));

			System.out.println("\nIs any User is exist with Id 111111 :"
					+ cassandraOps.exists(Users.class, 111111));
			System.out.println("Is any User is exist with Id 11101 :"
					+ cassandraOps.exists(Users.class, 11101));
			
			System.out.println("\nNo of Users available in Database is :"
					+ cassandraOps.count(Users.class));

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

	private static void printList(final List<Users> inResults) {

		for (Users user : inResults) {
			System.out.println("User Id is: " + user.getId());
			System.out.println("User Address is: " + user.getAddress());
			System.out.println("User Name is: " + user.getName());
		}
	}
}

User.java

package com.devjavasource.cassandra.dto;

import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;

@Table
public class User {
	@PrimaryKey
	private int id;

	private String address;
	private String name;

	public User(int id, String address, String name) {
		this.id = id;
		this.address = address;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public String getAddress() {
		return address;
	}

	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", address=" + address + ", name=" + name
				+ "]";
	}
}

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 :

Spring Data Cassandra Select Single User Example
=================================================
User Id is: 11103
User Address is: Nederland
User Name is: Joe

Spring Data Cassandra bulk User Selection Example
====================================================
User Id is: 11103
User Address is: Nederland
User Name is: Joe
User Id is: 11102
User Address is: California
User Name is: smith
User Id is: 11101
User Address is: Oakland
User Name is: john
====================================================
User Id is: 11103
User Address is: Nederland
User Name is: Joe
User Id is: 11102
User Address is: California
User Name is: smith
User Id is: 11101
User Address is: Oakland
User Name is: john
====================================================
User Id is: 11101
User Address is: Oakland
User Name is: john

Is any User is exist with Id 111111 :false
Is any User is exist with Id 11101 :true

No of Users available in Database is :3

Verify the data in cassandra :

Start cqlsh shell and use key space “devjavasource” and query
for the table Users.

1

You can download complete project, Here

SpringDataCassandraExample

*** Venkat – Happy leaning ****