- Spring Data Tutorial - Home
- Spring Data Apache Solr
- Overview
- Prerequisites
- Introduction
- What is Apache Solr?
- Getting Started
- Querying
- Features
- Conclusion
- Spring Data Cassandra
- Overview
- Prerequisites
- Introduction
- What is Cassandra?
- Getting Started
- Annotation AllowFiltering with Query Methods
- Partition and Clustering
- Coding hands-on on Partitioning and Clustering
- Features
- Conclusion
- Spring Data Couchbase
- Overview
- Prerequisites
- Introduction
- What is Couchbase?
- Getting Started
- Views
- CouchbaseTemplate
- Hands-on using CouchbaseTemplate
- Features
- Conclusion
- Spring Data Elasticsearch
- Overview
- Prerequisites
- Introduction
- What is ElasticSearch?
- Getting Started
- Querying
- Configuring ElasticsearchOperations bean
- Features
- Conclusion
- Spring Data JDBC
- Introduction
- Need of Spring Data JDBC
- Features
- Domain-Driven Design
- Prerequisites
- Getting Started
- Conclusion
- Spring Data JPA
- Background
- Introduction
- Prerequisites
- Getting Started
- Features
- Conclusion
- Spring Data MongoDB
- Overview
- Prerequisites
- Introduction
- What is MongoDB?
- Getting Started
- Query Methods
- Annotations
- Exposing REST end points
- Relationship
- Conclusion
- Spring Data Redis
- Overview
- Prerequisites
- Introduction
- What is Redis?
- Redis Java Clients
- Getting Started
- Features
- Conclusion
- Spring Data REST
- Background
- Introduction to Spring Data REST
- Prerequisites
- Getting Started
- Features
- Conclusion
- Spring Data Tutorial Useful Resources
- Spring Data Tutorial - Quick Guide
- Spring Data Tutorial - Useful Resources
- Spring Data Tutorial - Discussion
Getting Started with Spring Data Cassandra
Like other Spring−based projects, you can start from scratch by creating a maven or Gradle based project from your favorite IDE. Follow below step by step process or you can bypass the basic setup steps that are already familiar with.
Adding Dependencies.
If you have created normal Maven or Gradle projects then add below dependencies to your pom. For Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-cassandra</artifactId> </dependency>
Above one is the Spring Data Cassandra dependency. If you have created your project as Spring Boot or Starting with Spring Initializr then your final list of dependencies will look like this −
Note − The code sample and examples used in this tutorial has been created through Spring Initializr. The following is your final pom.xml file that is created when you choose Maven −
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.tutorialspoint</groupId>
<artifactId>Spring-Data-Cassandra</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Data-Cassandra</name>
<description>Spring Data Cassandra project using Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Creating Table
A table for Cassandra data base is equivalent to a model/entity, it is an actual domain object and it will be created as a POJO. Its maps columns to be persisted into the database. It uses annotation @Table from org.springframework.data.cassandra.core.mapping. Lets define our first table −
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
@Table("customer")
public class Customer {
@PrimaryKey
private Long id;
private String name;
public Customer() {
}
public Customer(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + "]";
}
}
@Table: We used to mark our domain object with this annotation to map Cassandra table. @PrimaryKey here we mark it for identity purpose. This annotation is from org.springframework.data.cassandra.core.mapping. We van also use @Id for identity purposes, which is from import org.springframework.data.annotation from Spring Data. We use @PrimaryKey annotation against a field if that field consist of partition and clustering columns. We will understand this concept in details in later section of this article. We can also use other annotations like @Column to name our column if it we dont want the name used in the class field and it is optional.
Creating a Repository
Lets define an interface which will be our repository −
import org.springframework.data.cassandra.repository.CassandraRepository;
import com.tutorialspoint.entity.Customer;
public interface CustomerRepository extends CassandraRepository<Customer, Long> {
}
The process of creating a repository is similar to the repository creation in any spring data-based project, the only difference here is that it extends CassandraRepository from org.springframework.data.cassandra.repository, which works on top of CrudRepository.
Configuring DataSource
We can configure Cassandra using application.properties file, using XML and using Java based configuration. We can choose either one among them. Lets discuss one by one.
XML Based Configurations
Below one is the equivalent XML configuration.
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:cassandra="http://www.springframework.org/schema/data/cassandra"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/cql http://www.springframework.org/schema/cql/spring-cql-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/cassandra http://www.springframework.org/schema/data/cassandra/spring-cassandra.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<cassandra:cluster id="cassandraCluster"
contact-points="127.0.0.1" port="9042" />
<cassandra:converter />
<cassandra:session id="cassandraSession" cluster-ref="cassandraCluster"
keyspace-name="tutorials_point" />
<cassandra:template id="cqlTemplate" />
<cassandra:repositories base-package="com.tutorialspoint.repository" />
<cassandra:mapping entity-base-packages="com.tutorialspoint.entity" />
</beans:beans>
Replace the cluster info, bucket and repositories details.
Java Based Configuration
Create a config file, say CassandraConfig, and extend AbstractCassandraConfiguration, this will ask to implement necessary methods which will be used for passing credentials as follows −
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
@Configuration
@EnableCassandraRepositories(basePackages = "com.tutorialspoint.repository")
public class CassandraConfig extends AbstractCassandraConfiguration {
@Override
protected String getKeyspaceName() {
return "tutorials_point";
}
@Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints("127.0.0.1");
cluster.setPort(9042);
cluster.setJmxReportingEnabled(false);
return cluster;
}
@Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
}
Using application.properties file
Below one is the majorly used configuration, just replace the credentials.
spring.data.cassandra.keyspace-name=tutorials_point spring.data.cassandra.contact-points=127.0.0.1 spring.data.cassandra.port=9042
Performing CRUD Operation
Now lets perform below some CRUD operation. We will try adding some customers to the above document, and retrieve some of them by their id or name. Following is the code for the same.
import java.util.Optional;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.tutorialspoint.entity.Customer;
import com.tutorialspoint.repository.CustomerRepository;
@SpringBootApplication
public class SpringDataCassandraApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataCassandraApplication.class, args);
}
@Bean
CommandLineRunner commandLineRunner(CustomerRepository customerRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
// Creating some entries
Customer customer1 = customerRepository.save(new Customer(1l, "Asad"));
System.out.println(customerRepository.save(customer1));
Customer customer2 = customerRepository.save(new Customer(2l, "Ali"));
System.out.println(customer2);
Customer customer3 = customerRepository.save(new Customer(3l, "John"));
System.out.println(customer3);
// Fetching entry
System.out.println(customerRepository.findById(1l));
// Find all entry
System.out.println(customerRepository.findAll());
// Update entry
Optional<Customer> customerOptional = customerRepository.findById(3l);
if (customerOptional.isPresent()) {
Customer customer = customerOptional.get();
customer.setName("John Montek");
System.out.println(customerRepository.save(customer));
}
// Deleting entry
customerRepository.delete(customer2);
// fetch all Entry
System.out.println(customerRepository.findAll());
}
};
}
}
The above code has used CommandLineRunner which will be executed on application startup. We have created four customers and saved them in the database and executed the method findById() to retrieve the customers. We also tried updating one of the records and re-retrieved to check if it has been updated. Finally we are deleting one of the records. Lets run the application as the Spring Boot App, below is the output.
Creating Entriess
Customer [id=1, name=Asad] Customer [id=2, name=Ali] Customer [id=3, name=John]
Finding one of the entry
Optional[Customer [id=1, name=Asad]]
Finding all entry
[Customer [id=1, name=Asad], Customer [id=2, name=Ali], Customer [id=3, name=John]]
Updating an entry
Customer [id=3, name=John Montek]
Deleted one of the entry and re-retrieved all entry
[Customer [id=1, name=Asad], Customer [id=3, name=John Montek]]