Connect to TiDB with Spring Boot
TiDB is a MySQL-compatible database, and Spring is a popular open-source container framework for Java. This document uses Spring Boot as the way to use Spring.
In this tutorial, you can learn how to use TiDB along with Spring Data JPA and Hibernate as the JPA provider to accomplish the following tasks:
- Set up your environment.
- Connect to your TiDB cluster using Hibernate and Spring Data JPA.
- Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.
Prerequisites
To complete this tutorial, you need:
- Java Development Kit (JDK) 17 or higher. You can choose OpenJDK or Oracle JDK based on your business and personal requirements.
- Maven 3.8 or higher.
- Git.
- A TiDB cluster.
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Cloud Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
Run the sample app to connect to TiDB
This section demonstrates how to run the sample application code and connect to TiDB.
Step 1: Clone the sample app repository
Run the following commands in your terminal window to clone the sample code repository:
git clone https://github.com/tidb-samples/tidb-java-springboot-jpa-quickstart.git
cd tidb-java-springboot-jpa-quickstart
Step 2: Configure connection information
Connect to your TiDB cluster depending on the TiDB deployment option you've selected.
- TiDB Cloud Serverless
- TiDB Cloud Dedicated
- TiDB Self-Managed
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
Click Connect in the upper-right corner. A connection dialog is displayed.
Ensure the configurations in the connection dialog match your operating environment.
- Connection Type is set to
Public
- Branch is set to
main
- Connect With is set to
General
- Operating System matches your environment.
- Connection Type is set to
Click Generate Password to create a random password.
Run the following command to copy
env.sh.example
and rename it toenv.sh
:cp env.sh.example env.shCopy and paste the corresponding connection string into the
env.sh
file. The example result is as follows:export TIDB_HOST='{host}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com export TIDB_PORT='4000' export TIDB_USER='{user}' # e.g. xxxxxx.root export TIDB_PASSWORD='{password}' export TIDB_DB_NAME='test' export USE_SSL='true'Be sure to replace the placeholders
{}
with the connection parameters obtained from the connection dialog.TiDB Cloud Serverless requires a secure connection. Therefore, you need to set the value of
USE_SSL
totrue
.Save the
env.sh
file.
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
Click Connect in the upper-right corner. A connection dialog is displayed.
In the connection dialog, select Public from the Connection Type drop-down list, and then click CA cert to download the CA certificate.
If you have not configured the IP access list, click Configure IP Access List or follow the steps in Configure an IP Access List to configure it before your first connection.
In addition to the Public connection type, TiDB Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Dedicated Cluster.
Run the following command to copy
env.sh.example
and rename it toenv.sh
:cp env.sh.example env.shCopy and paste the corresponding connection string into the
env.sh
file. The example result is as follows:export TIDB_HOST='{host}' # e.g. tidb.xxxx.clusters.tidb-cloud.com export TIDB_PORT='4000' export TIDB_USER='{user}' # e.g. root export TIDB_PASSWORD='{password}' export TIDB_DB_NAME='test' export USE_SSL='false'Be sure to replace the placeholders
{}
with the connection parameters obtained from the connection dialog.Save the
env.sh
file.
Run the following command to copy
env.sh.example
and rename it toenv.sh
:cp env.sh.example env.shCopy and paste the corresponding connection string into the
env.sh
file. The example result is as follows:export TIDB_HOST='{host}' export TIDB_PORT='4000' export TIDB_USER='root' export TIDB_PASSWORD='{password}' export TIDB_DB_NAME='test' export USE_SSL='false'Be sure to replace the placeholders
{}
with the connection parameters, and setUSE_SSL
tofalse
. If you are running TiDB locally, the default host address is127.0.0.1
, and the password is empty.Save the
env.sh
file.
Step 3: Run the code and check the result
Execute the following command to run the sample code:
makeRun the request script in another terminal session:
make requestCheck the Expected-Output.txt to see if the output matches.
Sample code snippets
You can refer to the following sample code snippets to complete your own application development.
For complete sample code and how to run it, check out the tidb-samples/tidb-java-springboot-jpa-quickstart repository.
Connect to TiDB
Edit the configuration file application.yml
:
spring:
datasource:
url: ${TIDB_JDBC_URL:jdbc:mysql://localhost:4000/test}
username: ${TIDB_USER:root}
password: ${TIDB_PASSWORD:}
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
database-platform: org.hibernate.dialect.TiDBDialect
hibernate:
ddl-auto: create-drop
After configuration, set the environment variables TIDB_JDBC_URL
, TIDB_USER
, and TIDB_PASSWORD
to the actual values of your TiDB cluster. The configuration file provides default settings for these environment variables. If you do not configure the environment variables, the default values are as follows:
TIDB_JDBC_URL
:"jdbc:mysql://localhost:4000/test"
TIDB_USER
:"root"
TIDB_PASSWORD
:""
Data management: @Repository
Spring Data JPA manages data through the @Repository
interface. To use the CRUD operations provided by JpaRepository
, you need to extend the JpaRepository
interface:
@Repository
public interface PlayerRepository extends JpaRepository<PlayerBean, Long> {
}
Then, you can use @Autowired
for automatic dependency injection in any class that requires the PlayerRepository
. This enables you to directly use CRUD functions. The following is an example:
@Autowired
private PlayerRepository playerRepository;
Insert or update data
playerRepository.save(player);
For more information, refer to Insert data and Update data.
Query data
PlayerBean player = playerRepository.findById(id).orElse(null);
For more information, refer to Query data.
Delete data
playerRepository.deleteById(id);
For more information, refer to Delete data.
Next steps
Learn more usage about the third-party libraries and frameworks used in this document, refer to their official documentation:
Learn the best practices for TiDB application development with the chapters in the Developer guide, such as Insert data, Update data, Delete data, Single table reading, Transactions, and SQL performance optimization.
Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Learn through the course for Java developers: Working with TiDB from Java.
Need help?
Ask questions on TiDB Community, or create a support ticket.