Connecting Java to Cassandra Database

Connecting Java to Cassandra Database

Referring to this article you will be able to implement a simple Java application that communicates with Cassandra Database and you will be able to understand how to do CRUD operations in Cassandra DB with Java. Please refer to my previous article to configure Cassandra on your local computer since it will be a great help to continuously understand this post. Connecting Java to Cassandra Database is very easy like MySQL – Java connectivity.

Please follow the steps are given below,

Firstly, you have to download the Cassandra Java Database Connectivity Driver (JDBC) from this link. Then you have to add it to your project. If you are using IntelliJ you can add Cassandra JDBC dependency to your pom file.

Then Create a Class for creating a database connection. There are few points needs to be understood. those are cluster, session, contact points, Keyspace, and replication factor.

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class DBConnector {

    private Cluster cluster;
    private Session session;

    public void connectdb(String seeds, int port) {
        this.cluster = Cluster.builder().addContactPoint(seeds).withPort(port).build();
        final Metadata metadata = cluster.getMetadata();

        for (final Host host : metadata.getAllHosts()) {
            System.out.println("driver version " + host.getCassandraVersion());
        }

        this.session = cluster.connect();
    }

    public Session getSession() {
        return this.session;
    }

    public void close() {
        cluster.close();
    }
}

Then you have to Create the Keyspace. The code is shown as below.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author bhanuka
 */
public class CreateKeySpace {

    public static void main(String[] args) {
        try {
            DBConnector connector = new DBConnector();
            connector.connectdb("localhost", 9042);

            final String createmovieKeySpace = "CREATE KEYSPACE IF NOT EXISTS movies_keyspace WITH "
                    + "replication = {'class' : 'SimpleStrategy','replication_factor' :3}";

            connector.getSession().execute(createmovieKeySpace);
            
            connector.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Then Create a Table.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author bhanuka
 */
public class CreateTable {

    public static void main(String[] args) {
        try {
            DBConnector connector = new DBConnector();
            connector.connectdb("localhost", 9042);

            final String createmovieTable = "CREATE TABLE IF NOT EXISTS movies_keyspace.movies"
                    + "(title varchar,year int, descreiption varchar, rating varchar, PRIMARY KEY (title, year))";

            connector.getSession().execute(createmovieTable);
            
            connector.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

After that you can insert, search, update and delete the data using below code examples respectively.

import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class InsertData {

    public static void main(String[] args) {
        try {
            DBConnector connector = new DBConnector();
            connector.connectdb("localhost", 9042);

            final String insertQuery = "INSERT INTO movies_keyspace.movies (title,year,descreiption,rating) "
                    + "VALUES (?,?,?,?)";

            PreparedStatement psInsert = connector.getSession().prepare(insertQuery);
            BoundStatement bsInsert = psInsert.bind("Annabelle", 2019, "Horror", "4.5");
            connector.getSession().execute(bsInsert);

            connector.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class SearchData {

    public static void main(String[] args) {
        try {
            DBConnector connector = new DBConnector();
            connector.connectdb("localhost", 9042);

            final String selectQuery = "SELECT * FROM movies_keyspace.movies WHERE title=? AND year= ?";

            PreparedStatement psSelect = connector.getSession().prepare(selectQuery);
            BoundStatement bsSelect = psSelect.bind("Fast Five", 2012);
            ResultSet rs = connector.getSession().execute(bsSelect);

            rs.forEach(rr -> {
                System.out.println("movie name : " + rr.getString("title"));
                System.out.println("movie desc : " + rr.getString("descreiption"));
                System.out.println("rating : " + rr.getString("rating"));
            });

            connector.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class UpdateData {

    public static void main(String[] args) {
        try {
            DBConnector connector = new DBConnector();
            connector.connectdb("localhost", 9042);

            final String updateQuery = "UPDATE movies_keyspace.movies SET rating= ? WHERE "
                    + "title= ? AND year = ?";

            PreparedStatement psUpdate = connector.getSession().prepare(updateQuery);
            BoundStatement bsUpdate = psUpdate.bind("10.0", "Annabelle", 2019);
            connector.getSession().execute(bsUpdate);

            connector.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bhanuka
 */
public class DeleteData {

    public static void main(String[] args) {
        try {
            DBConnector connector = new DBConnector();
            connector.connectdb("localhost", 9042);

            final String deleteQuery = "DELETE FROM movies_keyspace.movies WHERE title=? AND year= ?";

            PreparedStatement psDelete = connector.getSession().prepare(deleteQuery);
            BoundStatement bsDelete = psDelete.bind("Annabelle", 2019);
            connector.getSession().execute(bsDelete);

            connector.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Once you create the application successfully, then you will be able to understand this article “Connecting Java to Cassandra Database”
GIT Location – https://github.com/rajithabhanuka/LearnCassandra.git