Create the following folder structure:

pom.xml: (if using Gradle, replace pom.xml with build.gradle)
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.maxjava</groupId> <artifactId>SpringRESTAPICassandraDatastaxMapper</artifactId> <version>1.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.1.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.4</version> </dependency> <dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-mapper-runtime</artifactId> <version>4.17.0</version> </dependency> <dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-mapper-processor</artifactId> <version>4.17.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <version>3.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.13.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>
plugins { id 'java' id 'war' } java { sourceCompatibility = 17 targetCompatibility = 17 } group 'net.maxjava' version '1.0' repositories { mavenCentral() } dependencies { implementation group: 'org.springframework', name: 'spring-webmvc', version: '6.1.6' implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.15.4' implementation group: 'jakarta.annotation', name: 'jakarta.annotation-api', version: '3.0.0' implementation group: 'com.datastax.oss', name: 'java-driver-mapper-runtime', version: '4.17.0' compileOnly group: 'com.datastax.oss', name: 'java-driver-mapper-processor', version: '4.17.0' annotationProcessor group: 'com.datastax.oss', name: 'java-driver-mapper-processor', version: '4.17.0' compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.30' annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.30' }
Some notes about pom.xml:
- spring-webmvc for necessary Spring REST controllers and its dependencies
- jackson-databind is for the java object serialization and deserialization
- java-driver-query-builder and java-driver-mapper-runtime is needed for using Datastax mapper
- java-driver-mapper-processor is for processing Datastax mapper annotations
- jakarta.annotation-api is needed for annotations like @PostConstruct
- lombok to remove boilerplate code like get and set
- maven-compiler-plugin is for compiling the code using source version 17 and target version 17
- A war artifact will be created for deployment to servlet containers
Some notes about build.gradle:
- spring-webmvc for necessary Spring REST controllers and its dependencies
- jackson-databind is for the java object serialization and deserialization
- java-driver-query-builder and java-driver-mapper-runtime is needed for using Datastax mapper
- java-driver-mapper-processor is for processing Datastax mapper annotations
- jakarta.annotation-api is needed for annotations like @PostConstruct
- lombok to remove boilerplate code like get and set
- sourceCompatibility and targetCompatibility is for compiling the code using source version 17 and target version 17
- A war artifact will be created for deployment to servlet containers
web.xml:
<web-app> <display-name>Spring REST API with Cassandra using Datastax Mapper</display-name> <servlet> <servlet-name>SpringRESTAPICassandraDatastaxMapper</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myApplicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringRESTAPICassandraDatastaxMapper</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
Some notes about web.xml:
- org.springframework.web.servlet.DispatcherServlet is the servlet class for Spring
- /WEB-INF/myApplicationContext.xml is the location of the Spring context configuration file
myApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="controller,repository"/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> </beans>
Some notes about myApplicationContext.xml:
- <context:component-scan base-package="controller,repository"/> is for Spring to look for classes in specific packages to create beans
- <mvc:message-converters> is to specify library for json serialization and deserialization
This tutorial based on the following Cassandra Table structure, assuming the keyspace company exists:
CREATE TABLE company.customer ( last_name text, first_name text, created timestamp, phone text, PRIMARY KEY (last_name, first_name) );
Some notes about the table:
- last_name column is the partition key, while first_name is the clustering key
- for this tutorial we just use the partition key (last_name) to retrieve or delete the rows
MyController.java:
package controller; import repository.CustomerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import model.Customer; import java.util.List; @RestController @RequestMapping("/myapp") public class MyController { @Autowired private CustomerRepository customerRepository; @PutMapping("/customer") public void insertCustomer(@RequestBody Customer customer) { customerRepository.insertCustomer(customer); } @GetMapping("/customer") public List<Customer> getCustomerByLastName(@RequestParam("lastName") String lastName) { List<Customer> customerList = customerRepository.getCustomerByLastName(lastName); return customerList; } @DeleteMapping("/customer") public void deleteCustomerByLastName(@RequestParam("lastName") String lastName) { customerRepository.deleteCustomerByLastName(lastName); } }
Some notes about MyController.java:
- This is Spring REST API which putting @RestController will do the trick (and make sure the package of this class got scanned in bean creation)
- This class autowires CassandraRepository which is the bean to interact with the database.
- Providing some popular functions like insertCustomer, getCustomerByLastName and deleteCustomerByLastName to show insert, retrieve and delete
Customer.java:
package model; import lombok.Data; @Data public class Customer { private String lastName; private String firstName; private String created; private String phone; }
Some notes about Customer.java:
- This is the object used in the request body and response body of the REST APIs
CassandraRepository.java:
package repository; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.PagingIterable; import jakarta.annotation.PreDestroy; import model.Customer; import org.springframework.stereotype.Repository; import jakarta.annotation.PostConstruct; import java.net.InetSocketAddress; import java.time.Instant; import java.util.ArrayList; import java.util.List; @Repository public class CustomerRepository { private CqlSession cqlSession; private final String serverIP = "localhost"; private final int port = 9042; private CustomerDao customerDao; @PostConstruct private void init() { cqlSession = CqlSession.builder() .addContactPoint(new InetSocketAddress(serverIP, port)) .withLocalDatacenter("datacenter1") .build(); CustomerMapper customerMapper = new CustomerMapperBuilder(cqlSession).build(); customerDao = customerMapper.customerDao("company", "customer"); } @PreDestroy private void finish() { cqlSession.close(); } public void insertCustomer(Customer customer) { CustomerEntity customerEntity = new CustomerEntity(); customerEntity.setLastName(customer.getLastName()); customerEntity.setFirstName(customer.getFirstName()); customerEntity.setCreated(Instant.now()); customerEntity.setPhone(customer.getPhone()); customerDao.insertCustomer(customerEntity); } public List<Customer> getCustomerByLastName(String lastName) { List<Customer> customerList = new ArrayList<>(); PagingIterable<CustomerEntity> customerEntities = customerDao.findByLastName(lastName); for (CustomerEntity customerEntity : customerEntities) { Customer customer = new Customer(); customer.setLastName(customerEntity.getLastName()); customer.setFirstName(customerEntity.getFirstName()); customer.setCreated(customerEntity.getCreated().toString()); customer.setPhone(customerEntity.getPhone()); customerList.add(customer); } return customerList; } public void deleteCustomerByLastName(String lastName) { customerDao.deleteByLastName(lastName); } }
Some notes about CassandraRepository.java:
- @Repository to specify the class as Spring bean
- CustomerDao is thread-safe so a single instance is enough for the entire CassandraRepository bean
- @PostConstruct to specify init to run when the class is initiated, which is to create the cqlSession, customerMapper and customerDao objects
- This class supports insertCustomer, getCustomerByLastName and deleteCustomerByLastName
- Assume Cassandra is at localhost 9042, with keyspace "company" created, otherwise please use corresponding values
CustomerDao.java:
package repository; import com.datastax.oss.driver.api.core.PagingIterable; import com.datastax.oss.driver.api.mapper.annotations.Dao; import com.datastax.oss.driver.api.mapper.annotations.Delete; import com.datastax.oss.driver.api.mapper.annotations.Insert; import com.datastax.oss.driver.api.mapper.annotations.Select; @Dao public interface CustomerDao { @Select PagingIterable<CustomerEntity> findByLastName(String lastName); @Insert void insertCustomer(CustomerEntity customer); @Delete(entityClass = CustomerEntity.class) void deleteByLastName(String lastName); }
Some notes about CustomerDao.java:
- Annotate with @Dao to specify this interface will be used to create the data access object by Datastax Mapper
- Annotate the methods with @Select, @Insert and @Delete to specify these methods will be implemented by Datastax Mapper to do Select, Insert and Delete operations on Cassandra
CustomerMapper.java:
package repository; import com.datastax.oss.driver.api.mapper.annotations.DaoFactory; import com.datastax.oss.driver.api.mapper.annotations.DaoKeyspace; import com.datastax.oss.driver.api.mapper.annotations.DaoTable; import com.datastax.oss.driver.api.mapper.annotations.Mapper; @Mapper public interface CustomerMapper { @DaoFactory CustomerDao customerDao(@DaoKeyspace String keyspace, @DaoTable String table); }
Some notes about CustomerMapper.java:
- Annotate with @Mapper to specify this interface will be used to create the mapper object by Datastax Mapper
- Annotate the method with @DaoFactory to specify this method will be implemented to generate a data access object
CustomerEntity.java:
package repository; import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn; import com.datastax.oss.driver.api.mapper.annotations.Entity; import com.datastax.oss.driver.api.mapper.annotations.PartitionKey; import java.time.Instant; @Entity public class CustomerEntity { @PartitionKey private String lastName; @ClusteringColumn private String firstName; private Instant created; private String phone; public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Instant getCreated() { return created; } public void setCreated(Instant created) { this.created = created; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
Some notes about CustomerEntity.java:
- Annotate with @Entity to specify this class represents a Cassandra table
- Annotate the corresponding fields with @PartitionKey and @ClusteringColumn
Sample requests and responses(assume the war file is deployed to <CONTEXT_PATH>):
- Add a new record:
curl --request PUT '<CONTEXT_PATH>/myapp/customer' --header 'Content-Type: application/json' --data-raw ' { "firstName": "Ethan", "lastName": "Smith", "phone": "310-123-1234" }'
- Retrieve the record by last name
Response:curl --request GET '<CONTEXT_PATH>/myapp/customer?lastName=Smith'[ { "lastName": "Smith", "firstName": "Ethan", "created": "Sat Jun 01 23:40:42 PDT 2022", "phone": "310-123-1234" } ] - Add another record with same last name
curl --request PUT '<CONTEXT_PATH>/myapp/customer' --header 'Content-Type: application/json' --data-raw ' { "firstName": "Tom", "lastName": "Smith", "phone": "650-123-1234" }'
- Retrieve the record by same last name again
Response:curl --request GET '<CONTEXT_PATH>/myapp/customer?lastName=Smith'[ { "lastName": "Smith", "firstName": "Ethan", "created": "Sat Jun 01 23:40:42 PDT 2024", "phone": "310-123-1234" }, { "lastName": "Smith", "firstName": "Tom", "created": "Sat Jun 01 23:48:10 PDT 2024", "phone": "650-123-1234" } ] - Deleting records by the last name
curl --request DELETE '<CONTEXT_PATH>/myapp/customer?lastName=Smith'
- Retrieve the record by same last name again
Response status:curl --request GET '<CONTEXT_PATH>/myapp/customer?lastName=Smith'[]