Templates by BIGtheme NET

Spring Data Cassandra : Update data

In this Article, I will show How to update single and bulk data in
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 update 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 update 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 update() method of CassandraTemplate class, we can update single
or multiple records in Cassandra Database.

// To update a single User information in Database
final Users updatedUsers = cassandraOps.update(new Users(11104,
		"UK_updated", "Alex"));
		
// To update multiple User information at a time.
// Bulk update operation
final Users user1 = new Users(11105, "Australia", "Mike_updated");
final Users user2 = new Users(11106, "India", "Ram_updated");
final List<Users> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);

final List<Users> updatedUserList = cassandraOps.update(userList);

Five different types of update() methods are available
in Spring Data CassandraTemplate,

// Using this, we can update single Object data in Cassandra database.
<T> T update(T entity)

// Using this, we can update bulk data in Cassandra database.
<T> List<T> update(List<T> entities)

// We can update, with WriteOption 
<T> T update(T entity, WriteOptions options)
<T> List<T> update(List<T> entities, WriteOptions options)

// Update the given entity asynchronously
<T> List<T> updateAsynchronously(List<T> entities)
//This method is deprecate, better check before using in your code.

// Update the given entity asynchronously
//These two methods are deprecate, better check before using in your code.
<T> Cancellable updateAsynchronously(T entity, WriteListener<T> listener);

<T> Cancellable updateAsynchronously(T entity, 
WriteListener<T> listener, WriteOptions options);
// listener - is the listener class to receive notification of completion

What is WriteOption ?

Contains Query Options for Cassandra queries.
This controls the Consistency Tuning and Retry Policy for a Query.

we can create a WriteOptions instance with following constructor,

WriteOptions(ConsistencyLevel consistencyLevel, RetryPolicy retryPolicy)

(a) consistencyLevel – is the consistencyLevel associated
with Cassandra for this particular update operation.

Possible values are
ANY, ONE, TWO, THREE, QUOROM, LOCAL_QUOROM, EACH_QUOROM,
ALL, LOCAL_ONE, SERIAL, LOCAL_SERIAL.

Suppose If we pass ONE as consistencyLevel, that means if cluseter is down.
Then Cassandra server returns server fault message only after try
with only one active cluser in ring.

(b) retryPolicy – is the retryPolicy associated
with Cassandra for this particular update operation.

Possible values are
DEFAULT, DOWNGRADING_CONSISTENCY, FALLTHROUGH, LOGGING

Complete Source code is Here,
App.java

package com.devjavasource.cassandra.SpringDataCassandraExample;

import java.util.ArrayList;
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 Single Update Example");
			System.out.println("============================================");
			print(cassandraOps, 11104);
			// To update a single User information in Database
			final Users updatedUsers = cassandraOps.update(new Users(11104,
					"UK_updated", "Alex"));

			System.out.println("Updated User Id is: " + updatedUsers.getId()
					+ "\nUser information after update  ");
			System.out.println("============================================");

			print(cassandraOps, updatedUsers.getId());

			System.out.println("\nSpring Data Cassandra bulk Update Example");
			System.out.println("============================================");
			printList(cassandraOps, Arrays.asList(11105, 11106));

			// To update multiple User information at a time.
			// Bulk update operation
			final Users user1 = new Users(11105, "Australia", "Mike_updated");
			final Users user2 = new Users(11106, "India", "Ram_updated");
			final List<Users> userList = new ArrayList<>();
			userList.add(user1);
			userList.add(user2);

			final List<Users> updatedUserList = cassandraOps.update(userList);
			System.out.println("\n" + updatedUserList);
			System.out.println("\nUsers information after update  ");
			System.out.println("============================================");
			printList(cassandraOps, Arrays.asList(11105, 11106));

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

	private static void print(final CassandraOperations inCassandraOps,
			final int inId) {

		final String[] columns = new String[] { "id", "address", "name" };

		Select select = QueryBuilder.select(columns).from("users");
		select.where(QueryBuilder.eq("id", inId));

		final List<Users> results = inCassandraOps.select(select, Users.class);

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

	private static void printList(final CassandraOperations inCassandraOps,
			final List<Integer> inIdList) {

		final String[] columns = new String[] { "id", "address", "name" };

		Select select = QueryBuilder.select(columns).from("users");
		select.where(QueryBuilder.in("id", inIdList));

		final List<Users> results = inCassandraOps.select(select, Users.class);

		for (Users user : results) {
			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 Single Update Example
============================================
User Id is: 11104
User Address is: UK
User Name is: Alex
Updated User Id is: 11104
User information after update  
============================================
User Id is: 11104
User Address is: UK_updated
User Name is: Alex

Spring Data Cassandra bulk Update Example
============================================
User Id is: 11105
User Address is: Australia
User Name is: Mike
User Id is: 11106
User Address is: India
User Name is: Ram

[User [id=11105, address=Australia, name=Mike_updated], User [id=11106, address=India, name=Ram_updated]]

Users information after update  
============================================
User Id is: 11105
User Address is: Australia
User Name is: Mike_updated
User Id is: 11106
User Address is: India
User Name is: Ram_updated

Verify the data in cassandra :

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

3

You can download complete project, Here

SpringDataCassandraExample

*** Venkat – Happy leaning ****