Connect to TiDB with MyBatis

TiDB is a MySQL-compatible database, and MyBatis is a popular open-source Java ORM.

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

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

MyBatis - 图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-mybatis-quickstart.git
  2. cd tidb-java-mybatis-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.

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

    MyBatis - 图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-mybatis-quickstart repository.

Connect to TiDB

Edit the MyBatis configuration file mybatis-config.xml:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="cacheEnabled" value="true"/>
  8. <setting name="lazyLoadingEnabled" value="false"/>
  9. <setting name="aggressiveLazyLoading" value="true"/>
  10. <setting name="logImpl" value="LOG4J"/>
  11. </settings>
  12. <environments default="development">
  13. <environment id="development">
  14. <!-- JDBC transaction manager -->
  15. <transactionManager type="JDBC"/>
  16. <!-- Database pool -->
  17. <dataSource type="POOLED">
  18. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  19. <property name="url" value="${tidb_jdbc_url}"/>
  20. <property name="username" value="${tidb_user}"/>
  21. <property name="password" value="${tidb_password}"/>
  22. </dataSource>
  23. </environment>
  24. </environments>
  25. <mappers>
  26. <mapper resource="${mapper_location}.xml"/>
  27. </mappers>
  28. </configuration>

Be sure to replace ${tidb_jdbc_url}, ${tidb_user}, and ${tidb_password} with the actual values of your TiDB cluster. Also, replace ${mapper_location} with the path of your mapper XML configuration file. For multiple mapper XML configuration files, you need to add a <mapper/> tag for each. Then, define the following function:

  1. public SqlSessionFactory getSessionFactory() {
  2. InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
  3. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  4. }

Insert data

Add a node in the mapper XML and add a function with the same name in the interface class configured in the mapper.namespace attribute of the XML configuration file:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.pingcap.model.PlayerMapper">
  4. <insert id="insert" parameterType="com.pingcap.model.Player">
  5. insert into player (id, coins, goods)
  6. values (#{id,jdbcType=VARCHAR}, #{coins,jdbcType=INTEGER}, #{goods,jdbcType=INTEGER})
  7. </insert>
  8. </mapper>

For more information, refer to Insert data.

Query data

Add a node in the mapper XML and add a function with the same name in the interface class configured in the mapper.namespace attribute of the XML configuration file. Specifically, if you use resultMap as the return type for MyBatis query functions, make sure that the <resultMap/> node is configured correctly.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.pingcap.model.PlayerMapper">
  4. <resultMap id="BaseResultMap" type="com.pingcap.model.Player">
  5. <constructor>
  6. <idArg column="id" javaType="java.lang.String" jdbcType="VARCHAR" />
  7. <arg column="coins" javaType="java.lang.Integer" jdbcType="INTEGER" />
  8. <arg column="goods" javaType="java.lang.Integer" jdbcType="INTEGER" />
  9. </constructor>
  10. </resultMap>
  11. <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
  12. select id, coins, goods
  13. from player
  14. where id = #{id,jdbcType=VARCHAR}
  15. </select>
  16. </mapper>

For more information, refer to Query data.

Update data

Add a node in the mapper XML and add a function with the same name in the interface class configured in the mapper.namespace attribute of the XML configuration file:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.pingcap.model.PlayerMapper">
  4. <update id="updateByPrimaryKey" parameterType="com.pingcap.model.Player">
  5. update player
  6. set coins = #{coins,jdbcType=INTEGER},
  7. goods = #{goods,jdbcType=INTEGER}
  8. where id = #{id,jdbcType=VARCHAR}
  9. </update>
  10. </mapper>

For more information, refer to Update data.

Delete data

Add a node in the mapper XML and add a function with the same name in the interface class configured in the mapper.namespace attribute of the XML configuration file:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.pingcap.model.PlayerMapper">
  4. <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
  5. delete from player
  6. where id = #{id,jdbcType=VARCHAR}
  7. </delete>
  8. </mapper>

For more information, refer to Delete data.

Next steps

Need help?

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

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