Spring boot spring data Cassandra crud example

Spring boot spring data Cassandra crud example tutorial that explains how to create a REST api using Spring boot 2, Spring data Cassandra and Cassandra database.

This tutorial is a modification of the tutorial Spring Boot Spring Data H2 database tutorial.

Adding Spring data Cassandra maven dependency

You should install Python 2.7 and Cassandra community in order to follow this tutorial.

You can download Python 2.7 from this link  .

You can also download cassandra 3.11.6 from this link.

Cassandra has a problems with Python 3.x and JAVA 11. This is why i am using an old version of Python and jdk1.8.0_221.

The dependency to be added to the maven POM file is the following :

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>

Setting up Cassandra database using JAVA configuration file

The configuration file of Cassandra is the following:

package com.javasneo.todolist.config;
import com.datastax.oss.driver.api.core.CqlSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.cassandra.SessionFactory;
import org.springframework.data.cassandra.config.*;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.core.convert.CassandraConverter;
import org.springframework.data.cassandra.core.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.core.mapping.SimpleUserTypeResolver;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;

@Configuration
@EnableCassandraRepositories(
  basePackages = "com.javasneo.todolist.repository")
public class CassandraConfig extends AbstractCassandraConfiguration {
  @Override
  protected String getKeyspaceName() {
    return "abderrahmen";
  }
  
  public String getContactPoints() {
    return "localhost";
  }

  @Override
  protected String getLocalDataCenter() {
    return "datacenter1";
  }

  @Bean
  @Primary
  public CqlSessionFactoryBean session() {

    CqlSessionFactoryBean session = new CqlSessionFactoryBean();
    session.setContactPoints(getContactPoints());
    session.setKeyspaceName(getKeyspaceName());
    session.setLocalDatacenter(getLocalDataCenter());
    return session;
  }

  @Bean
  @Primary
  public SessionFactoryFactoryBean sessionFactory(CqlSession session, CassandraConverter converter) {
    SessionFactoryFactoryBean sessionFactory = new SessionFactoryFactoryBean();
    sessionFactory.setSession(session);
    sessionFactory.setConverter(converter);
    sessionFactory.setSchemaAction(SchemaAction.NONE);
    return sessionFactory;
  }

  @Bean
  @Primary
  public CassandraMappingContext mappingContext(CqlSession cqlSession) {

    CassandraMappingContext mappingContext = new CassandraMappingContext();
    mappingContext.setUserTypeResolver(new SimpleUserTypeResolver(cqlSession));
    return mappingContext;
  }

  @Bean
  @Primary
  public CassandraConverter converter(CassandraMappingContext mappingContext) {
    return new MappingCassandraConverter(mappingContext);
  }

  @Bean
  public CassandraOperations cassandraTemplate(SessionFactory sessionFactory, CassandraConverter converter) {
    return new CassandraTemplate(sessionFactory, converter);
  }

}

Here, i set set the keyspace as abderrahmen and i set the local data center as datacenter1 (the default value). That keyspace is used when creating our Todo table in Cassandra.

Updating the REST API to use Cassandra database

In order to update the Spring Boot REST API example, we will :

  • Update the model to add Cassandra annotations
  • Update repository that makes the CRUD operations
  • Update service that uses this repository
  • Update the controller to use this service

Rest API Model

We will add the Cassandra annotations to the Todo entity in order to make it managed by Spring Data Cassandra.

The required annotations are :

  • @Table : to make the class a Cassandra table
  • @PrimaryKey : to make a field a primary key

In this class, we can get rid of Getters, Setters and constructors by using lombok. But, i don’t do it for the sake of simplicity and to make the beginners understand the code.

The code of the class is the following :

package com.javasneo.todolist.model;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import java.util.UUID;

@Table
public class Todo {

  @PrimaryKey
  private UUID id;
  private String name;
  private String description;

  public Todo() {
  }

  public Todo(UUID id, String name, String description) {
    this.id = id;
    this.name = name;
    this.description = description;
  }

  public UUID getId() {
    return id;
  }

  public void setId(UUID id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setDescription(String description) {
    this.description = description;
  }
}

Rest API Repository

The repository is a java interface with no javaclass implementing it. This is a spring Data Cassandra feature that auto-generates the CRUD code for us based on an interface that we specify.

The code of the repository is the following :

package com.javasneo.todolist.repository;

import com.javasneo.todolist.model.Todo;
import org.springframework.data.cassandra.repository.CassandraRepository;

import java.util.UUID;

public interface TodoRepository extends CassandraRepository<Todo, UUID> {
}

The TodoRepository interface should extend the Spring Data Cassandra interface CassandraRepository and give two parameters to that interface :

  • The first one is the Type of the Entity that we will generate the CRUD code for.
  • The second one is the type of the primary key of the entity (the id attribute in the Todo class is of type UUID)

Rest API Service

The service layer of the application is composed by the interface of the service and its implementation.

The source code of the interface is the following :

package com.javasneo.todolist.service;
import com.javasneo.todolist.model.Todo;
import java.util.List;
import java.util.UUID;

public interface TodoService {
  List<Todo> getAll();
  Todo create(Todo todo);
  Todo update(Todo todo);
  void delete(UUID id);
}

The source code of the implementation is the following :

package com.javasneo.todolist.service;

import com.javasneo.todolist.model.Todo;
import com.javasneo.todolist.repository.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class TodoServiceImpl implements TodoService{
  @Autowired
  TodoRepository todoRepository;

  public List<Todo> getAll(){
    List<Todo> todoList = new ArrayList<Todo>();
    todoRepository.findAll().forEach(todo -> todoList.add(todo));
    return todoList;
  }

  public Todo create(Todo todo)
  {
    return todoRepository.save(new Todo(UUID.randomUUID(), todo.getName(), todo.getDescription()));
  }
  
  public Todo update(Todo todo)
  {
    return todoRepository.save(todo);
  }

  public void delete(UUID id)
  {
    todoRepository.deleteById(id);
  }

}

Rest API controller

The controller uses the service layer to provide the CRUD endpoints.

The source code of the controller is the following :

package com.javasneo.todolist.controller;

import com.javasneo.todolist.model.Todo;
import com.javasneo.todolist.model.TodoListResponse;
import com.javasneo.todolist.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/todos")
@CrossOrigin()
public class TodoController {

  @Autowired
  TodoService todoService;

  @RequestMapping(method = RequestMethod.GET)
  public TodoListResponse todos (){
    List<Todo> todoList = todoService.getAll();
    TodoListResponse todoListResponse = new TodoListResponse();
    todoListResponse.setTodos(todoList);
    return todoListResponse;
  }

  @RequestMapping(method = RequestMethod.POST)
  public Todo addtodo (@RequestBody Todo todo){
    return todoService.create(todo);
  }

  @RequestMapping(method = RequestMethod.PUT)
  public Todo updateTodo (@RequestBody Todo todo){
    return todoService.update(todo);
  }

  @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
  public void deleteTodo (@PathVariable("id") UUID id){
    todoService.delete(id);
  }

}

Cassandra table creation

The script of the Todo table creation is the following :

create keyspace abderrahmen with replication={'class':'SimpleStrategy', 'replication_factor':1};
use abderrahmen;
 
CREATE TABLE todo(
   id uuid PRIMARY KEY,
   name text,
   description text
);

We run cqlsh executable present in the bin directory of Cassandra. Then, we run the commands above. The Cassandra database should be up and running (we should run cassandra.bat file present in the bin directory before running cqlsh)

Spring Boot REST API Testing

Before being able to test the restful webservice, we should run cassandra by running cassandra.bat present in the bin folder of the unzipped cassandra folder.

If you want to know how to test the endpoints using Postman, please check the part 1 of these series of tutorials that deal with Spring Boot 2 REST API.

In order to check the data in Cassandra, we use cqlsh.bat present in the bin directory of Cassandra community edition. The cqlsh executable gives us a prompt that allow us to run SQL queries.

We may run « select * from todo » to check the content of the todo table.

conclusion

This spring boot spring data Cassandra crud example tutorial arrives at its end.

You may check also our core java tutorial to learn core java from scratch. Please keep tuned because we will release more tutorials about Spring Boot, unit testing, integration testing and other important subjects.

In order to get our latest updates, please feel free to like our how to program facebook page.

The source code is present in this spring boot spring data Cassandra crud example git repository.

Post a Comment

Previous Post Next Post