Using Cassandra as storage for your Data is quite straightforward in Spring Boot as we have a starter POM ready for that. Let’s see how to do it.
If you are developing a simple Web application, all you need are two dependencies. From the CLI execute:
$ spring init -dweb,data-cassandra -artifactId data-cassandra-demo
The following dependencies will be added:
<?xml version="1.0" encoding="UTF-8"?><project>
<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>
</dependency>
</dependencies>
</project>
Before we start coding, it is important that we provide port, keyspace-name and contact-points properties for connection’s info, via spring.data.cassandra:
spring.data.cassandra.keyspace-name=mykeyspace spring.data.cassandra.contact-points=acme.com spring.data.cassandra.port=9042
In order to create your mapping model use @org.springframework.data.cassandra.mapping.Table and @org.springframework.data.cassandra.mapping.PrimaryKey as in the following example:
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
@Table
public class Customer {
@PrimaryKey private int id;
private String name;
}
In this example, @Table identifies a domain object to be persisted to Cassandra as a table and @PrimaryKey identifies the primary key field of the entity.
Then, you can create your Repository objects using the @Query object to retrieve data from Cassandra:
public interface CustomerRepository extends CrudRepository<Customer, String> {
@Query(value = "SELECT * FROM customer WHERE name=?0")
public List<Customer> findByName(String name);
}
Found the article helpful? if so please follow us on Socials