In this Article, I will show How to connect to Cassandra database from java.
What is Cassandra Session and Cluster objects and How to create.
How to perform basic CRUD operations.
Tools used :
1) eclipse version Luna 4.4.1.
2) Maven 3.3.3
3) Apache Cassandra 2.1.6 Server.
4) cassandra-driver-core 2.1.6.
If you are completely new to Apache Cassandra,
please refer apache-cassandra-quick-start
Prerequisites :
1) Cassandra Server should be up and running.
2) key space should be created with name “devJavaSource”
Steps to be followed :
1) Create a maven project in eclipse.
2) Add cassandra-driver-core 2.1.6 jar file as dependency in pom.xml file.
3) Start Cassandra server.
4) Write a simple java program.
5) Demo
1) Create a maven project in eclipse:
In eclipse, Go to File -> New -> Others in eclipse and
Select Maven -> Maven Project.
In our case, we want a simple maven project so we will enter org.apache.maven.archetypes
in filter and then select row with Artifact-id as maven-archetype-quickstart.
Now we have to create a template, enter ArticfactId and GroupId.

Now maven project is created, with name CassandraCURDOperationsExample.
2) Add cassandra-driver-core 2.1.6 jar file as dependency in pom.xml file :
Cassandra java driver cassandra-driver-core 2.1.6 jar is required to run java program,
So add this as dependency in pom.xml file.
<dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>2.1.6</version> </dependency>
3) Start Cassandra server :
Go to your home directory, where cassandra server is installed or extracted.
Command to start Casandra server is,
C:\apache-cassandra-2.1.6\bin> cassandra.bat -f
4) Write a simple java program :
Before writing a java program, we should know what is session and cluster objects.
How these objects can be used to execute queries.
(a) How to create or get Cassandra session object.
What is a Cluster?
Cluster is an main entry point of the driver.
We can create cluster object as given,
Cluster.builder().addContactPoint(<
addContactPoint() – Adds a contact point to the cluster.
adress – address the address of the node to connect to.
// Here 127.0.0.1 is the address of the node.
final Cluster cluster = Cluster.builder()
.addContactPoint("127.0.0.1").build();
// cluster.getClusterName() - To get Cluster Name
// cluster.getDriverVersion() - To get Driver Version
// cluster.getConfiguration() - To get cluster Configurations
// cluster.getMetadata() - To get Cluster Metadata
// cluster.getMetrics() - To get Metrics associated with cluster.
What is a Session?
A session (com.datastax.driver.core.Session) holds connections to a Cassandra cluster,
allowing it to be queried.
How to get or create a Session object?
(a) cluster.connect() – Creates a new session on this cluster and initialize it.
(b) connect(keyspace) – Creates a new session on this cluster, initialize it and sets the
keyspace to the provided one.
(c) cluster.newSession() – Creates a new session on this cluster but does not initialize it.
How to execute DB Query on Cassandra Session object :
session() and executeAsync() are two methods on session object to execute CQL queries.
session.execute(<< query >> | <
session.executeAsync(<< query >> | <
Difference between session() and executeAsync() is,
executeAsync() executes the provided query asynchronously.
Complete example is Here,
App.java
package com.devjavasource.cassandra.CassandraCURDOperationsExample;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
public class App {
public static void main(String[] args) {
// Connect to the cluster and keyspace "devjavasource"
final Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1")
.build();
final Session session = cluster.connect("devjavasource");
System.out.println("*********Cluster Information *************");
System.out.println(" Cluster Name is: " + cluster.getClusterName() );
System.out.println(" Driver Version is: " + cluster.getDriverVersion() );
System.out.println(" Cluster Configuration is: " + cluster.getConfiguration() );
System.out.println(" Cluster Metadata is: " + cluster.getMetadata() );
System.out.println(" Cluster Metrics is: " + cluster.getMetrics() );
// Retrieve all User details from Users table
System.out.println("\n*********Retrive User Data Example *************");
getUsersAllDetails(session);
// Insert new User into users table
System.out.println("\n*********Insert User Data Example *************");
session.execute("INSERT INTO users (id, address, name) VALUES (11104, 'USA', 'Stuatr')");
getUsersAllDetails(session);
// Update user data in users table
System.out.println("\n*********Update User Data Example *************");
session.execute("update users set address = 'USA NEW' where id = 11104");
getUsersAllDetails(session);
// Delete user from users table
System.out.println("\n*********Delete User Data Example *************");
session.execute("delete FROM users where id = 11104");
getUsersAllDetails(session);
// Close Cluster and Session objects
System.out.println("\nIs Cluster Closed :" + cluster.isClosed());
System.out.println("Is Session Closed :" + session.isClosed());
cluster.close();
session.close();
System.out.println("Is Cluster Closed :" + cluster.isClosed());
System.out.println("Is Session Closed :" + session.isClosed());
}
private static void getUsersAllDetails(final Session inSession){
// Use select to get the users table data
ResultSet results = inSession.execute("SELECT * FROM users");
for (Row row : results) {
System.out.format("%s %d %s\n", row.getString("name"),
row.getInt("id"), row.getString("address"));
}
}
}
5) Demo :
Select App.java and right click “Run As” -> “Java Application”.
*********Cluster Information ************* Cluster Name is: cluster1 Driver Version is: 2.1.6 Cluster Configuration is: com.datastax.driver.core.Configuration@27d415d9 Cluster Metadata is: com.datastax.driver.core.Metadata@5c18298f Cluster Metrics is: com.datastax.driver.core.Metrics@31f924f5 *********Retrive User Data Example ************* Joe 11103 Nederland smith 11102 California john 11101 Oakland *********Insert User Data Example ************* Joe 11103 Nederland smith 11102 California john 11101 Oakland Stuatr 11104 USA *********Update User Data Example ************* Joe 11103 Nederland smith 11102 California john 11101 Oakland Stuatr 11104 USA NEW *********Delete User Data Example ************* Joe 11103 Nederland smith 11102 California john 11101 Oakland Is Cluster Closed :false Is Session Closed :false Is Cluster Closed :true Is Session Closed :true
Download the source code
You can download the source code here: CassandraCURDOperationsExample
*** Venkat – Happy leaning ****


