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.

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:

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-mybatis-quickstart.git 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.

    • Connection Type is set to Public
    • Branch is set to main
    • Connect With is set to General
    • Operating System matches your environment.
  4. Click Generate Password to create a random password.

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

Connect to TiDB

Edit the MyBatis configuration file mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="false"/> <setting name="aggressiveLazyLoading" value="true"/> <setting name="logImpl" value="LOG4J"/> </settings> <environments default="development"> <environment id="development"> <!-- JDBC transaction manager --> <transactionManager type="JDBC"/> <!-- Database pool --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="${tidb_jdbc_url}"/> <property name="username" value="${tidb_user}"/> <property name="password" value="${tidb_password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="${mapper_location}.xml"/> </mappers> </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:

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

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:

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

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.pingcap.model.PlayerMapper"> <resultMap id="BaseResultMap" type="com.pingcap.model.Player"> <constructor> <idArg column="id" javaType="java.lang.String" jdbcType="VARCHAR" /> <arg column="coins" javaType="java.lang.Integer" jdbcType="INTEGER" /> <arg column="goods" javaType="java.lang.Integer" jdbcType="INTEGER" /> </constructor> </resultMap> <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap"> select id, coins, goods from player where id = #{id,jdbcType=VARCHAR} </select> </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:

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

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

For more information, refer to Delete data.

Next steps

Need help?

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

Was this page helpful?