Java Spring Boot REST Server with CockroachDB

🕓 45 minutes

What you’ll learn

How to setup your application for :

  • connecting to the CockroachDB database
  • getting data from REST API
  • providing data to REST API from the database.

In this tutorial, we will create a simple java component with Java Spring Boot scaffolder with a connection to CockroachDB database storage. We want to expose a single REST endpoint for getting the basic client data information, creating a microservice CRUD layer above the DB storage.

clientDataDB

Project source

This example project can be cloned from: [email protected]:innobank/aia-spring-cockroachdb.git

Prerequisites

Steps

Open your IDE, import the created component and start coding:

  • Add these maven dependencies to your pom.xml file:

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.3.3.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.3.3.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.21.Final</version>
    </dependency>
    <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.11</version>
    </dependency>
  • Define jpa entity Client. This simple table will store the basic client data:

    • Generate getters and setters with your IDE
    • NOTE: if your table name is different from the model class name, you should specify the table name inside the @Table annotation.
    01 import javax.persistence.Entity;
    02 import javax.persistence.GeneratedValue;
    03 import javax.persistence.Id;
    04 import javax.persistence.Table;
    05
    06 @Entity
    07 @Table(name = "client_data")
    08 public class Client {
    09
    10 @Id @GeneratedValue
    11 private Long id;
    12
    13 private String username;
    14 private String firstname;
    15 private String surname;
    16
    17 //...getters + setters
    18 }
  • Create a new ClientRepository, which is a basic CRUD interface for Spring Boot data DB access:

    01 import org.example.service.model.Client;
    02 import org.springframework.data.jpa.repository.JpaRepository;
    03 import org.springframework.stereotype.Repository;
    04
    05 @Repository
    06 public interface ClientRepository extends JpaRepository<Client, Long> {
    07 Client getClientByUsername(String username);
    08 }
  • Create a new controller and put all the parts together

    01 import org.example.service.model.Client;
    02 import org.example.service.repository.ClientRepository;
    03 import org.slf4j.Logger;
    04 import org.slf4j.LoggerFactory;
    05 import org.springframework.beans.factory.annotation.Autowired;
    06 import org.springframework.http.HttpStatus;
    07 import org.springframework.http.ResponseEntity;
    08 import org.springframework.web.bind.annotation.GetMapping;
    09 import org.springframework.web.bind.annotation.PathVariable;
    10 import org.springframework.web.bind.annotation.RestController;
    11
    12 import java.util.List;
    13
    14 @RestController("/clients")
    15 public class ClientController {
    16
    17 private static final Logger LOG = LoggerFactory.getLogger(ClientController.class);
    18
    19 @Autowired
    20 private ClientRepository clientRepository;
    21
    22 public ClientController(ClientRepository clientRepository) {
    23 super();
    24 this.clientRepository = clientRepository;
    25 }
    26
    27 @GetMapping
    28 private ResponseEntity<List<Client>> getAll() {
    29 List<Client> clients = clientRepository.findAll();
    30
    31 if(clients.size() <= 0) {
    32 return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
    33 }
    34
    35 return new ResponseEntity<>(clients, HttpStatus.OK);
    36 }
    37
    38 @GetMapping("/{username}")
    39 private ResponseEntity<Client> getClientByUsername(@PathVariable String username) {
    40 LOG.info("Get data for username: {}", username);
    41 Client client = clientRepository.getClientByUsername(username);
    42
    43 if(client == null) {
    44 return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    45 }
    46 return new ResponseEntity<>(client, HttpStatus.OK);
    47 }
    48 }
    49
  • Next prepare the database configuration:

  • Now change the configuration in config/application.yaml:

    • Fill {db name},{db user} and {db password} according to your configuration
    • Make sure you follow yaml syntax (especially whitespaces)
    server:
    port: 8080
    spring:
    main:
    banner-mode: off
    zipkin:
    enabled: false
    datasource:
    url: jdbc:postgresql://localhost:26257/{db name}}
    username: {db user}
    password: {db password}
    driver-class-name: org.postgresql.Driver
    jpa:
    properties:
    hibernate:
    dialect: org.hibernate.dialect.PostgreSQL95Dialect
    management:
    endpoints:
    web:
    exposure:
    include: health, prometheus
  • Try to build and run the application in your IDE. After startup, you should be able to access your new controller’s swagger: http://localhost:8080/swagger/index.html

clientDataDBSwagger1

Deploy to CodeNOW

If your code works in the local development, you are ready to push your changes to GIT and try to build and deploy your new component version to the CodeNOW environment.

What’s next?

See our other developer tutorials: