maven usage of Mybatis and springboot usage

Posted by PURU on Mon, 06 Sep 2021 19:50:32 +0200

Maven use

  1. Create Maven project and add dependency in pom
 <dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
    </dependencies>

Here I have inserted mybatis, MySQL and junit tests

2. mybatis core configuration in resources

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&amp;useSSL=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/demo/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

These properties are mainly configured
And the last point!!! It is very important to register your mapper!!!

<mappers>
        <mapper resource="com/example/demo/mapper/UserMapper.xml"/>
    </mappers>
  1. Because operations such as referencing the core configuration, establishing factories and so on are necessary steps for each use of mybatis, integrate them into a tool class, mybatisUtil

The official documents list: each application based on MyBatis takes an instance of SqlSessionFactory as the core. An instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder. SqlSessionFactory builder can build a SqlSessionFactory instance from an XML Configuration file or a pre configured Configuration instance.

Building an instance of SqlSessionFactory from an XML file is very simple. It is recommended to use the resource file under the classpath for configuration. However, you can also use any input stream instance, such as an input stream constructed with a file path string or a file:// URL. MyBatis contains a tool class called Resources, which contains some practical methods to make it easier to load resource files from the classpath or other locations.

package com.example.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
  1. Generally speaking, we obtain the core configuration, construct the project, and finally obtain the most important sqlsession. During the test, we can obtain the mapper through this sqlsession, so as to operate the database

  2. Then, it is similar to jdbc to establish entity classes and dao interfaces, but mybatis greatly simplifies jdbc and does not need to use the interface to implement a large number of repetitive template statements. Instead, it is more focused on the configuration file of functional business to replace the operation of sql, that is, xxxmapper.xml

    This interface is used to map with this xml
    The id here is the method name in the interface, the resultType here is the type we want to return, and the select below is the database operation we want to perform. This xml file can be configured with many such operations. Compared with jdbc, if we want to perform such operations, a lot of template code is omitted

<?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.example.demo.mapper.UserMapper">
    <select id="queryAll" resultType="com.example.demo.entity.User">
    select * from mybatis.user
  </select>
    <select id="queryById" resultType="com.example.demo.entity.User">
    select * from user where id=#{id}
  </select>
</mapper>
  1. Then you can test the mapper
package com.example.demo.mapper;

import com.example.demo.entity.User;
import com.example.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {
    private SqlSessionFactory sqlSessionFactory;
    @Test
    public void selectTest(){
       SqlSession sqlSession= MybatisUtils.getSqlSession();
       //Get mapper
       UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        List<User> users=userMapper.queryAll();
        for(User user:users){
            System.out.println(user.toString());
        }
        sqlSession.close();
    }
}

Topics: Java Maven Spring Boot