Skip to content

Latest commit

 

History

History
280 lines (189 loc) · 11.4 KB

dev-guide-sample-application-java-hibernate.md

File metadata and controls

280 lines (189 loc) · 11.4 KB
title summary
Connect to TiDB with Hibernate
Learn how to connect to TiDB using Hibernate. This tutorial gives Java sample code snippets that work with TiDB using Hibernate.

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.

Note:

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

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:

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

Step 2: Configure connection information

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

  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.

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

    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.

    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:

    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:

    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 to true.

  7. Save the env.sh file.

  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. 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.

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

    cp env.sh.example env.sh
  5. Copy 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.

  6. Save the env.sh file.

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

    cp env.sh.example env.sh
  2. Copy 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 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.

  3. Save the env.sh file.

Step 3: Run the code and check the result

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

    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:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.TiDBDialect</property>
        <property name="hibernate.connection.url">${tidb_jdbc_url}</property>
        <property name="hibernate.connection.username">${tidb_user}</property>
        <property name="hibernate.connection.password">${tidb_password}</property>
        <property name="hibernate.connection.autocommit">false</property>

        <!-- Required so a table can be created from the 'PlayerDAO' class -->
        <property name="hibernate.hbm2ddl.auto">create-drop</property>

        <!-- Optional: Show SQL output for debugging -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
    </session-factory>
</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:

public SessionFactory getSessionFactory() {
    return new Configuration()
            .configure("hibernate.cfg.xml")
            .addAnnotatedClass(${your_entity_class})
            .buildSessionFactory();
}

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

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

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

Query data

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

For more information, refer to Query data.

Delete data

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

For more information, refer to Delete data.

Next steps

Need help?

Ask questions on TiDB Community, or create a support ticket.

Ask questions on TiDB Community, or create a support ticket.