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:
First, we annotate the main class with @SpringBootApplication, which tells Spring Boot to start up a web application.
We then implement the CommandLineRunner interface, which allows us to run some code after the application has started up.
In the run method, we use the CassandraOperations object that was automatically injected into the class by Spring Boot to get a Cassandra session.
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.
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.
Comments