Connect to TiDB with Hibernate

TiDB is a MySQL-compatible database, and Hibernate is a popular open-source Java ORM. Starting from version 6.0.0.Beta2, Hibernate supports TiDB dialect, which fits TiDB features well.

In this tutorial, you can learn how to use TiDB and Hibernate to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using Hibernate.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

Hibernate - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.

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:

If you don’t have a TiDB cluster, you can create one as follows:

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:

  1. git clone https://github.com/tidb-samples/tidb-java-hibernate-quickstart.git
  2. cd tidb-java-hibernate-quickstart

Step 2: Configure connection information

Connect to your TiDB cluster depending on the TiDB deployment option you’ve selected.

  • TiDB Serverless
  • TiDB Dedicated
  • TiDB Self-Hosted
  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. Ensure the configurations in the connection dialog match your operating environment.

    • Endpoint Type is set to Public
    • Branch is set to main
    • Connect With is set to General
    • Operating System matches your environment.

    Hibernate - 图2

    Tip

    If your program is running in Windows Subsystem for Linux (WSL), switch to the corresponding Linux distribution.

  4. Click Generate Password to create a random password.

    Hibernate - 图3

    Tip

    If you have created a password before, you can either use the original password or click Reset Password to generate a new one.

  5. Run the following command to copy env.sh.example and rename it to env.sh:

    1. cp env.sh.example env.sh
  6. Copy and paste the corresponding connection string into the env.sh file. The example result is as follows:

    1. export TIDB_HOST='{host}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com
    2. export TIDB_PORT='4000'
    3. export TIDB_USER='{user}' # e.g. xxxxxx.root
    4. export TIDB_PASSWORD='{password}'
    5. export TIDB_DB_NAME='test'
    6. export USE_SSL='true'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

    TiDB Serverless requires a secure connection. Therefore, you need to set the value of USE_SSL to true.

  7. Save the env.sh file.

  8. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  9. Click Connect in the upper-right corner. A connection dialog is displayed.

  10. Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.

    For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.

  11. Run the following command to copy env.sh.example and rename it to env.sh:

    1. cp env.sh.example env.sh
  12. Copy and paste the corresponding connection string into the env.sh file. The example result is as follows:

    1. export TIDB_HOST='{host}' # e.g. tidb.xxxx.clusters.tidb-cloud.com
    2. export TIDB_PORT='4000'
    3. export TIDB_USER='{user}' # e.g. root
    4. export TIDB_PASSWORD='{password}'
    5. export TIDB_DB_NAME='test'
    6. export USE_SSL='false'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

  13. Save the env.sh file.

  14. Run the following command to copy env.sh.example and rename it to env.sh:

    1. cp env.sh.example env.sh
  15. Copy and paste the corresponding connection string into the env.sh file. The example result is as follows:

    1. export TIDB_HOST='{host}'
    2. export TIDB_PORT='4000'
    3. export TIDB_USER='root'
    4. export TIDB_PASSWORD='{password}'
    5. export TIDB_DB_NAME='test'
    6. export USE_SSL='false'

    Be sure to replace the placeholders {} with the connection parameters, and set USE_SSL to false. If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  16. Save the env.sh file.

Step 3: Run the code and check the result

  1. Execute the following command to run the sample code:

    1. make
  2. Check 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-hibernate-quickstart repository.

Connect to TiDB

Edit the Hibernate configuration file hibernate.cfg.xml:

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!-- Database connection settings -->
  8. <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
  9. <property name="hibernate.dialect">org.hibernate.dialect.TiDBDialect</property>
  10. <property name="hibernate.connection.url">${tidb_jdbc_url}</property>
  11. <property name="hibernate.connection.username">${tidb_user}</property>
  12. <property name="hibernate.connection.password">${tidb_password}</property>
  13. <property name="hibernate.connection.autocommit">false</property>
  14. <!-- Required so a table can be created from the 'PlayerDAO' class -->
  15. <property name="hibernate.hbm2ddl.auto">create-drop</property>
  16. <!-- Optional: Show SQL output for debugging -->
  17. <property name="hibernate.show_sql">true</property>
  18. <property name="hibernate.format_sql">true</property>
  19. </session-factory>
  20. </hibernate-configuration>

Be sure to replace ${tidb_jdbc_url}, ${tidb_user}, and ${tidb_password} with the actual values of your TiDB cluster. Then, define the following function:

  1. public SessionFactory getSessionFactory() {
  2. return new Configuration()
  3. .configure("hibernate.cfg.xml")
  4. .addAnnotatedClass(${your_entity_class})
  5. .buildSessionFactory();
  6. }

When using this function, you need to replace ${your_entity_class} with your own data entity class. For multiple entity classes, you need to add a .addAnnotatedClass(${your_entity_class}) statement for each. The preceding function is just one way to configure Hibernate. If you encounter any issues in the configuration or want to learn more about Hibernate, refer to the Hibernate official documentation.

Insert or update data

  1. try (Session session = sessionFactory.openSession()) {
  2. session.persist(new PlayerBean("id", 1, 1));
  3. }

For more information, refer to Insert data and Update data.

Query data

  1. try (Session session = sessionFactory.openSession()) {
  2. PlayerBean player = session.get(PlayerBean.class, "id");
  3. System.out.println(player);
  4. }

For more information, refer to Query data.

Delete data

  1. try (Session session = sessionFactory.openSession()) {
  2. session.remove(new PlayerBean("id", 1, 1));
  3. }

For more information, refer to Delete data.

Next steps

Need help?

Ask questions on the Discord, or create a support ticket.