spring boot tidb

Author: Qizhi Wang (Senior Software Engineer at PingCAP) 
Editors: Fendy Feng, Tom Dewan, Rick Golba

Web application developers are on a never-ending quest to build better applications faster and more easily. This post introduces two great tools—Spring Boot and TiDB—that simplify your development process, enabling you to easily realize your application goals. Spring Boot is a popular open source tool that helps you build standalone production-grade web applications faster and easier. TiDB is an open source SQL database with a simplified and distributed architecture, elastic scalability, and MySQL compatibility. It helps you process and analyze your application data, however large it may be, with ease and in real time. 

In this article, we’ll use Spring Boot to build a sample game application, with TiDB as the database. In this app, each player has a unique ID. They also have two attributes—coins and goods—that they use to trade with each other. 

Now, let’s start to explore how to build this game application. Before we get started, if you’d like to know what the final application looks like, you can find its complete source code on GitHub. 

Install JDK and Apache Maven 

To get started, install a Java Development Kit (JDK) and Apache Maven to manage the application dependencies. For detailed guidance, refer to the documentation on how to Install JDK and how to Install Maven.

Create and launch your TiDB cluster

You can either create a local TiDB cluster or a TiDB Cloud free cluster, which is a fully-managed Database-as-a-Service (DBaaS).

Get the application code

  1. Download or clone the sample application repository to your local environment, and then navigate to the spring-jpa-hibernate directory.
  2. Create a blank application with the same dependencies. Use Spring Initializr to generate the same structure as the sample game. Fill the fields as shown below.

    Spring Initializr Configuration

When you finish the configuration, the application can run, but only when you use the MySQL dialect. This is because Hibernate supports the TiDB dialect in version 6.0.0.Beta2 and later. However, the default dependency of Spring Data Java™ Persistence API (JPA) on Hibernate is 5.6.4.Final. Therefore, we recommend you make the following changes to pom.xml.

1. Exclude the jakarta packages introduced in Spring Data JPA, as shown in the following dependency file. Change the dependency file from:

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

To:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
    <exclusion>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core-jakarta</artifactId>
    </exclusion>
</exclusions>
</dependency>

2. Introduce Hibernate dependencies from 6.0.0.Beta2 or later, as shown in this dependency file:

<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>6.0.0.CR2</version>
</dependency>

After you make these changes, you have a blank Spring Boot application with the same dependencies as our game application.

Run the application

In the blank application you just created, Hibernate creates a player_jpa table within the test database. When you make requests using the application’s RESTful API, these requests run database transactions on the TiDB cluster.

If you use a TiDB Cloud cluster, navigate to the src/main/resources directory and in the application.yml file, set spring.datasource.url, spring.datasource.username, and spring.datasource.password.

spring:
  datasource:
    url: jdbc:mysql://localhost:4000/test
    username: root
    #    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
    database-platform: org.hibernate.dialect.TiDBDialect
    hibernate:
      ddl-auto: create-drop

If you set the password to 123456, the connection string you get in TiDB Cloud is:

mysql --connect-timeout 15 -u root -h xxx.tidbcloud.com -P 4000 -p

Of course, when you create an actual project, we recommend that you use a more secure password.

Next, you can set the parameters as follows:

spring:
  datasource:
    url: jdbc:mysql://xxx.tidbcloud.com:4000/test
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
    database-platform: org.hibernate.dialect.TiDBDialect
    hibernate:
      ddl-auto: create-drop

After you make these changes, you can run the application. 

Open a terminal session and navigate to the directory:

cd <path>/tidb-example-java/spring-jpa-hibernate

Build and run the application with Make.

make

HTTP requests

After the service is up and running, you can send the HTTP requests to the backend application. http://localhost:8080 is the base URL that provides services. You can use many different HTTP requests such as Postman and cURL requests to use this application. In this tutorial, we use Postman requests to show you how to use this application. 

Use Postman requests

Download this configuration file and import it into Postman as shown here:

import the collection into Postman

Create players

Click on the Create tab and the Send button to send a POST request to http://localhost:8080/player/. The return value is the number of players added, which is expected to be 1.

Postman-Create a player

Get player information by ID

Click on the GetByID tab and the Send button to send a GET request to http://localhost:8080/player/1. The return value is the information of the player with ID 1.

Postman-GetByID

Get player information in bulk by limit

Click on the GetByLimit tab and the Send button to send a GET request to http://localhost:8080/player/limit/3. The return value is a list of information for up to 3 players.

Postman-GetByLimit

Get player information by page

Click on the GetByPage tab and the Send button to send a GET request to http://localhost:8080/player/page?index=0&size=2. The return value is the page with index 0, with 2 players per page. The return value also contains the paging information such as the offset, totalPages, and sort order.

Postman-GetByPage

Count players

Click the Count tab and the Send button to send a GET request to http://localhost:8080/player/count. The return value is the number of players.

Postman-Count

Player trading

Click on the Trade tab and the Send button to send a PUT request to http://localhost:8080/player/trade. The request parameters are the seller’s ID (sellID), the buyer’s ID (buyID), the amount of goods purchased , and the number of coins consumed for the purchase price.

The return value indicates whether the transaction succeeded. When the seller doesn’t have enough goods, the buyer doesn’t have enough coins, or there is a database error, the database transaction guarantees that the trade is not successful and no player’s coins or goods are lost.

Postman-Trade

Wrapping Up 

In this post, you’ve learned how to build a game application with Spring Boot and TiDB, and seen how quickly and easily you can do it. If you want to learn more implementation details about this game, see the Implementation Details

If you encounter problems or have questions, contact us through Twitter and our Slack channel. You can also join TiDB Internals to share your thoughts and feedback with us.

Keeping reading: 
Using Retool and TiDB Cloud to Build a Real-Time Kanban in 30 Minutes
Analytics on TiDB Cloud with Databricks
Build a Better Github Insight Tool in a Week? A True Story

Qizhi Wang

About the Author

Qizhi Wang

More From Qizhi Wang

Subscribe to Stay Informed!

TiDB Cloud logo-black

TiDB Cloud

Get the massive scale and resiliency of TiDB databases in a fully managed cloud service

TiDB logo-black

TiDB

TiDB is effortlessly scalable, open, and trusted to meet the real-time needs of the digital enterprise