DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Boot Application With Spring REST and Spring Data MongoDB

Trending

  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • Exactly-Once Processing: Myth vs Reality
  • The Agentic Agile Office: Streamlining Enterprise Agile With Autonomous AI Agents
  • Testing AI-Infused Apps: A Dual-Layer Framework for AI Quality Assurance
  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring Boot + CockroachDB in Kubernetes/OpenShift

Spring Boot + CockroachDB in Kubernetes/OpenShift

In this post, we look at how to use CockroachDB inside a Spring Boot application. Read on for the details.

By 
Alex Soto user avatar
Alex Soto
·
Jun. 10, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
9.5K Views

Join the DZone community and get the full member experience.

Join For Free

TL;DR: In this post, we look at how to use CockroachDB inside a Spring Boot application. Read on for the details.

In my previous post, I showed why CockroachDB might help you if you need a cloud-native SQL database for your application. I explained how to install it in Kubernetes/OpenShift and how to validate that the data is replicated correctly.

In this post, I am going to show you how to use Cockroach DB in a Spring Boot application. Notice that Cockroach DB is compatible with PostgresSQL driver, so in terms of configuration, it is almost the same.

In this post, I assume that you have already a Cockroach DB cluster running in Kubernetes cluster as explained in my previous post.

For this example, I am using Fabric8 Maven Plugin to smoothly deploy a Spring Boot application to Kubernetes without having to worry so much about creating resources, creating Dockerfile and so on. Everything is automatically created and managed.

For this reason, pom.xml looks like:

<?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>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/>
		<!-- lookup parent from repository -->
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>io.fabric8</groupId>
				<artifactId>fabric8-maven-plugin</artifactId>
				<version>3.5.39</version>
				<executions>
					<execution>
						<goals>
							<goal>build</goal>
							<goal>resource</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Notice that apart from defining Fabric8 Maven Plugin, I am also defining to use Spring Data JPA to make the integration between Spring Boot and JPA easier from the point of view of the developer.

Then, you need to create a JPA entity and Spring Data CRUD repository to interact with JPA.

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // ....
  }
import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer, Long> {
}

Also, we need to create a controller who is responsible to get incoming requests, use the repository to make queries to DB, and return results back to the caller.

@RestController
public class CustomerController {

    @Autowired
    CustomerRepository customerRepository;

    @GetMapping("/init")
    public void initializeDb() {
        customerRepository.save(new Customer("Alex", ""));
        customerRepository.save(new Customer("Ada", ""));
        customerRepository.save(new Customer("Alexandra", ""));
    }

    @GetMapping("/customer")
    public @ResponseBody Iterable<Customer> getCustomers() {
        return customerRepository.findAll();
    }

}

Finally, you need to configure JPA to use the desired driver and dialect. In the case of Spring Boot, this is done in application.properties file.

spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL94Dialect
spring.datasource.url=jdbc:postgresql://cockroachdb-public:26257/customers?sslmode=disable
spring.jpa.show-sql=true
spring.datasource.username=myuser
spring.datasource.password=

The most important part here is that we need to use the PostgeSQL94 dialect. Notice that in url, we are using the postgresql jdbc url form. That's fine, since Cockroach uses the Postgres driver.

Now we need to create the database (customers) and the user (myuser) as configured in application.properties. To make it so, you just need to run cockroach shell and run some SQL commands:

oc run cockroachdb -it --image=cockroachdb/cockroach --rm --restart=Never     -- sql --insecure --host=cockroachdb-public

CREATE USER myuser;
CREATE DATABASE customers;
GRANT ALL ON DATABASE customers TO myuser;

Finally, you can deploy the application by running mvn clean fabric8:deploy. After that, the first time might take longer since needs to pull Docker images, and you can start sending queries to the service.

As you can see, it is really easy to start using a cloud-native DB like Cockroach DB in Spring Boot. If you want, you can do exactly the same as in my previous post and start running queries to each of the nodes to validate that data is available correctly.

The code can be found here.

Spring Framework Spring Boot CockroachDB Database Docker (software) application Spring Data POST (HTTP) Data (computing)

Published at DZone with permission of Alex Soto. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Boot Application With Spring REST and Spring Data MongoDB

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook