AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Spring Data with Cassandra

In this Refactorizando entry on “Example of Spring Data with Cassandra and Docker,” we will see how to integrate Spring Data with Cassandra. For an introduction to Cassandra, click here.

Starting and Configuring Cassandra with Docker

Starting Cassandra

To begin our integration of Cassandra with a Spring Boot application, the first thing we need to do is start a Cassandra database. For this purpose, we will use the following Docker command for its execution:

$ docker run -p 9042:9042 cassandra:latest

With the previous command, we have started the latest version of Cassandra.

Configuring Cassandra

Once the Docker image is running, we will enter Cassandra. To do this, we need to first obtain the process in which it is running:

docker ps

We look at the process identifier of Cassandra and copy it for the next step.

docker exect -it <processID> bash

Once inside, we execute the following command:

cqlsh

Create keyspace:

CREATE KEYSPACE mykeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};

Access the created keyspace.

use mykeyspace

Create table:

CREATE TABLE Car( id uuid PRIMARY KEY, model text, description text, color text);

Spring Boot Configuration with Apache Cassandra

Maven Dependencies in our Spring Data with Cassandra Example

The best way to create a Spring Boot application from scratch is to go to its initializr page and add the required dependencies. Once we have generated and downloaded the project, we need to make sure that we have the Cassandra dependency.

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

Connection Configuration

For connecting to Cassandra, there are three mandatory properties:

  • Contact-points: The hostname or IP address of the Cassandra node.
  • Keyspace-name: The namespace where data replication is defined across nodes.
  • Port: The connection port, usually 9042.

Starting from version 4.0, it is necessary to specify the local-datacenter to avoid routing requests to remote datacenters.

In our properties file located at src/resources/application.yml, we will write the following configuration:

spring:
  data:
    cassandra:
      keyspace-name: mykeyspace
      contact-points: 127.0.0.1
      port: 9042
      local-datacenter: datacenter1

Or, if you prefer, you can also write it programmatically as follows:

@Configuration
public class CassandraConfig extends AbstractCassandraConfiguration {
 
    @Override
    protected String getKeyspaceName() {
        return "cassandra";
    }
 
    @Bean
    public CassandraClusterFactoryBean cluster() {
        CassandraClusterFactoryBean cluster = 
          new CassandraClusterFactoryBean();
        cluster.setContactPoints("127.0.0.1");
        cluster.setPort(9142);
        return cluster;
    }
 
    @Bean
    public CassandraMappingContext cassandraMapping() 
      throws ClassNotFoundException {
        return new BasicCassandraMappingContext();
    }
}

Configuration of Repositories with Cassandra

Just like with any database when using JPA with Spring Boot, it is necessary to create a Repository class that extends CassandraRepository in this case.

public interface CarRepository extends CassandraRepository<Car, UUID> {
  List<Tutorial> findByModel(String model);
}

Similar to using Spring Data with JpaRepository or CrudRepository, we have default methods like save(), findOne(), findById(), findAll(), count(), delete(), deleteById(), etc. Moreover, without the need to create queries, we have options like findBy<Table Fields>. It’s best to refer to the official documentation.

Creating the entity object.

@Table
@Getter
@Setter
public class Car {
  @PrimaryKey
  private UUID id;

  private String model;

  private String description;

  private String color;
}

Creating API Controller

Next, we are going to create a Controller that will have four operations: GET, POST, UPDATE, DELETE.

@RestController
@RequestMapping("/api/cars")
@RequiredArgsConstructor
public class CarController {

    private final CarService carservice;

    @GetMapping()
    public ResponseEntity<List<Car>> getAllcars() {

        return new ResponseEntity<>(carservice.findAll(), HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Car> getCarById(@PathVariable("id") String id) {

        return new ResponseEntity<>(carservice.findById(UUID.fromString(id)), HttpStatus.OK);
    }

    @PostMapping()
    public ResponseEntity<Car> createCar(@RequestBody Car car) {

        return new ResponseEntity<>(carservice.saveCar(car), HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Car> updateCar(@PathVariable("id") String id, @RequestBody Car car) {

        if (carservice.existById(UUID.fromString(id))) {
            return new ResponseEntity<>(carservice.saveCar(car), HttpStatus.ACCEPTED);
        }

        throw new IllegalArgumentException("Car with id " + id + "not found");
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<HttpStatus> deleteCar(@PathVariable("id") String id) {

        carservice.deleteCar(UUID.fromString(id));

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

}

Testing the Example of Spring Data with Apache Cassandra

You can download the complete example from our GitHub by clicking here.

Creating a car object:

Send a request to http://localhost:8080/api/cars:

{
    "id": "f8fa0e2e-326f-11eb-adc1-0242ac120002",
    "model": "focus",
    "description": "small car",
    "color": "rojo"
}

Result:

{ "id": "f8fa0e2e-326f-11eb-adc1-0242ac120002", "model": "focus", "description": "small car", "color": "rojo"}

We can check in the database.

select * from car;

Consulta en Cassandra | Ejemplo de Spring Data con Cassandra y Docker
Cassandra Query

Fetching a car object:

Execute http://localhost:8080/api/cars/f8fa0e2e-326f-11eb-adc1-0242ac120002

and we get:

{
    "id": "f8fa0e2e-326f-11eb-adc1-0242ac120002",
    "model": "focus",
    "description": "small car",
    "color": "rojo"
}

Deleting a car object:

Execute the command http://localhost:8080/api/cars/f8fa0e2e-326f-11eb-adc1-0242ac120002 using the DELETE verb.

And we verify the result in the database:

Verificando la tabla de Car en Cassandra
Ceck table Car

The result is empty.

Conclusion

In this Example of Spring Data with Cassandra and Docker, we have seen the basic integration to connect our Spring Boot application with Cassandra. If you are already familiar with Spring Data, the integration is quite straightforward, requiring only knowledge of some parameters to configure the connection with Cassandra.

You can download the complete example from our GitHub by clicking here.

If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!

Leave a Reply

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