How to start Spring Data Cassandra with SpringBoot

Apache Cassandra database is a NoSql solution for scalability & high availability. In the tutorial, JavaSampleApproach will show you how to start Spring Data Cassandra by sample code.

Related article:
How to start SpringBoot ElasticSearch using Spring Data


I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE
– DataStax Community Edition for Apache Cassandra: v3.9.0

II. Practice

Step to do:
– Set up Apache Cassandra
– Create SpringBoot project
– Create a mapping model
– Create a Cassandra repository
– Create a test client
– Run & check result

1. Set up Apache Cassandra

Download Apache Cassandra:
– For Linux, go to the site Downloading Cassandra.
– For Windows, go to the site DataStax Distribution.

In the tutorial, environment: {Windows 10, Apache Cassandra – v3.9.0} to demo. After downloading, we have a file: datastax-ddc-64bit-3.9.0.msi. Now just double click on datastax-ddc-64bit-3.9.0.msi then do step by step to install.

Now start Cassandra server:

cassandra start sever

Open Cassandra CQL Shell to create Cassandra table:

– Create Cassandra keyspace with name javasampleapproach:

– Create customer table for javasampleapproach keyspace:

– Create an index on firstname column:

springboot-cassandra create table

2. Create SpringBoot project

– Using SpringToolSuite, create a SpringBoot project. Then add data-cassandra dependency:

3. Create a mapping model

– Create Customer.java:

@Table: identifies a domain object to be persisted to Cassandra as a table.
@PrimaryKey: identifies the primary key field of the entity.

4. Create a Cassandra repository

– Open application.properties, configure spring.data.cassandra:

– Spring Data supports basic operations for Cassandra. But more limited than JPA repositories, so we need use @Query.

5. Create a test client

– Use repository: CustomerRepository

Implement 3 functions:
clearData() is used to empty customer table.
saveData() is used to persist Customer entities to Cassandra.
lookup() is used to load all records and show all on console.

6. Run & check result

– Build & Run the project with SpringBoot App mode.
-> Meet an InvalidQueryException exception when executing lookup function – findCustomerHasAgeGreaterThan(int age):

-> Solution:
Use ALLOW FILTERING in Query:

– Build & Run the project with SpringBoot App mode again.
Logs:

Cassandra CQL Shell:

springboot-cassandra - select after saving

III. Sourcecode

SpringDataCassandra


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*