top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

SpringBoot with Cassandra DB Example


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.cassandra.core.CassandraOperations;

import com.datastax.oss.driver.api.core.CqlSession;

@SpringBootApplication
public class CassandraSpringBootExample implements CommandLineRunner {

    @Autowired
    private CassandraOperations cassandraOperations;

    public static void main(String[] args) {
        SpringApplication.run(CassandraSpringBootExample.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        CqlSession session = cassandraOperations.getSession();
        session.execute("CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'}");
        session.execute("CREATE TABLE IF NOT EXISTS mykeyspace.mytable (id int PRIMARY KEY, name text)");
        session.execute("INSERT INTO mykeyspace.mytable (id, name) VALUES (1, 'John Doe')");
    }

}



Explanation:

  1. First, we annotate the main class with @SpringBootApplication, which tells Spring Boot to start up a web application.

  2. We then implement the CommandLineRunner interface, which allows us to run some code after the application has started up.

  3. In the run method, we use the CassandraOperations object that was automatically injected into the class by Spring Boot to get a Cassandra session.

  4. The session is used to execute some Cassandra commands. In this case, we create a keyspace and a table if they don't already exist, and then insert a single row into the table.

  5. The CqlSession class is part of the Cassandra Java driver and is used to establish a connection to a Cassandra cluster and execute CQL (Cassandra Query Language) commands.

Note: This example assumes that Cassandra is already set up and running. If not, you'll need to install Cassandra and start a cluster before running this code.



2 views

Recent Posts

See All

Machine Learning : KNN model

Introduction to K-Nearest Neighbors (KNN) Algorithm in Machine Learning: K-Nearest Neighbors (KNN) is one of the simplest and most...

Comments


bottom of page