Spring Boot CQRS Query Example (2024) | TechGeekNext

Spring Boot CQRS Query Example (2024)

In the previous example we have implemented Command Part of Spring Boot CQRS Example. In this tutorial, we will explore the next part that is Query from CQRS (Command Query Responsibility Segregation) with Axon Framework and Axon Server as an event store.

CQRS also utilised in many microservices as a suitable design pattern to follow when you have to operate or separate read and write operations.

What is CQRS?
Ans:

CQRS (Command Query Responsibility Segregation) is a microservices design pattern that divides reading and writing into two models. Every method should be either a Command that performs an action or a Query that returns data. CQRS divides reads and writes into independent models, updating data with commands and reading data with queries.

The name Command Query Responsibility Segregation denotes that Command is used to handle POST, PUT, PATCH, DELETE - (WRITE) operations, whilst Query is used to handle GET - (READ) operation.

CQRS Query operation Flow

Spring Boot CQRS Query Part

Query Rest Controller

Create rest controller for handling rest endpoint to get the employees from the database.

  1. The QueryGateway interface and the DefaultQueryGateway implementation are provided by Axon.
  2. The query gateway provides a number of methods for sending a query and waiting for one or more results synchronously, with a timeout, or asynchronously.
package com.techgeeknext.query.controller;

import org.axonframework.messaging.responsetypes.ResponseTypes;
import org.axonframework.queryhandling.QueryGateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class EmployeeQueryController {
    @Autowired
    QueryGateway queryGateway;

    @GetMapping("/employees")
    public List<EmployeeResponse> getEmployees() {
        GetEmployeeQuery employeeQuery = new GetEmployeeQuery();
        return  queryGateway.query
                (employeeQuery,
                ResponseTypes.multipleInstancesOf(EmployeeResponse.class))
                .join();
    }
}

Query Employee Response Model

Create Employee model class to return the response.

package com.techgeeknext.query.controller;

import lombok.Data;

import java.io.Serializable;

@Data
public class EmployeeResponse implements Serializable {

    private static final long serialVersionUID = 3490459292051533428L;
    private long employeeId;
    private String name;
    private String address;
    private String role;
}

Take a look at our suggested posts:

Query Handler

Create a class to handle the query handler function for getting the employee from the database using JPA Repository.

  1. By annotating an object with @QueryHandler, it can declare a number of Query Handler methods in Axon.
  2. The method's stated arguments specify which messages the method will receive.
  3. findAll() method is form Jpa Repository which will returns all employees from the database.
package com.techgeeknext.query.eventhandler;

import com.techgeeknext.entity.Employee;
import com.techgeeknext.query.controller.EmployeeResponse;
import com.techgeeknext.query.controller.GetEmployeeQuery;
import com.techgeeknext.repository.EmployeeRepository;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class EmployeeQueryHandler {
    @Autowired
    EmployeeRepository employeeRepository;

    @QueryHandler
    public List<EmployeeResponse> getEmployees(GetEmployeeQuery employeeQuery){

        List<EmployeeResponse> employeeResponses = new ArrayList<>();
        Optional<List<Employee>> employees = Optional.ofNullable(employeeRepository.findAll());

        if(employees.isPresent()){
            for (Employee empObj: employees.get()){
                EmployeeResponse response = new EmployeeResponse();
                BeanUtils.copyProperties(empObj,response);
                employeeResponses.add(response);
            }
        }

        return employeeResponses;
    }
}

Test the CQRS Microservice

  1. Prerequisite : Run the Axon Server as per the steps given here.
  2. Start the Spring Boot Application by running spring-boot:run or by running main class.
  3. POST - To test Command Query
    Open POSTMAN, use the rest endpoint as http://localhost:8080/employee and provide the employee details in the body. Spring Boot CQRS Command Output
  4. GET - To test Query part
    Open POSTMAN, use the rest endpoint as http://localhost:8080/employees and click on Send button. Spring Boot CQRS Query Output
  5. AXON Dashboard
    Once Axon Server started, goto to axon dashboard on http://localhost:8888/ and click on Search -> aggregateIdentifier = "5ad2b608-b22e-4f4a-bd99-79260706eadb" (for more details click on About the query language) -> Click on Search. Spring Boot CQRS Query Output
  6. Database tables
    Once we run the Spring Boot application CQRS - SAGA related tables would get created and with POST rest endpoint employee data gets stored in the table. Open the h2 console in web browser at http://localhost:8080/h2-console. Spring Boot CQRS Query Output Spring Boot CQRS Query Output

Download Source Code

The full source code for this article can be found on below.
Download it here - Spring Boot CQRS Example


Recommendation for Top Popular Post :