How to set up MyBatis data source?

To configure the data source for MyBatis, you first need to specify the information of the data source in the MyBatis configuration file. Below is an example configuration file:

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mybatis/mapper.xml"/>
    </mappers>
</configuration>

The data source type in the configuration file is specified as POOLED using the element, which also includes details such as database driver, connection URL, username, and password. These configuration details can be modified according to actual requirements.

Additionally, you also need to load this configuration file in the MyBatis configuration class and create an SqlSessionFactory object.

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

In this example, the configuration file named “mybatis-config.xml” is loaded, and a SqlSessionFactory object is created using the SqlSessionFactoryBuilder. Next, we can use this SqlSessionFactory object to obtain a SqlSession and perform database operations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds