Steps to establish a connection with the database and execute query statements using the Mybatis persistence layer framework

1. In general, using mybatis to execute SQL statements can be executed in the following steps

1. Create an ordinary maven project and import dependencies:
open the official document of mybatis https://mybatis.org/mybatis-3/zh/index.html , the following steps are carried out in accordance with the guidelines of the official document. The first of course is to import dependencies

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

2. Create an instance of SqlSessionFactory:
According to the introduction of official documents, sqlSession in mybatis is used to execute sql statements instead of Statement. If you want to obtain sqlSession, you must create sqlSessionFactory. As the name suggests, this Factory is used to produce instances of SqlSesssion. So to create sqlSessionFactory, according to the guidelines of official documents, copy the code to create sqlSessionFactory.

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

3. Write the xml configuration file needed to create an instance of SqlSessionFactory:
in the code for creating sqlSession

String resource = "org/mybatis/example/mybatis-config.xml";

The configuration file is used in this place. Create the sqlSessionFactory configuration file to configure the url, user name, and user password to connect to the database. Also register the mapper here. So we need to write a configuration file, the official configuration file demonstration:

<?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="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

4. The preparation work is over here, you can use sqlSessionFactory to create sqlSession:

SqlSession sqlSession = MybatisUtils.getSqlSession();

5. Use this SqlSession instance to execute SQL statements:
This part is introduced in detail in the second section

Second, use mybatis to execute a sql statement step

1. Create a maven project, import dependencies in pom.xml and avoid resources not being exported:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--父工程-->
    <groupId>com.wt</groupId>
    <artifactId>MybatisStudy</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis01</module>
    </modules>

    <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!--在build中配置resource,防止资源不导出-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

    <properties>
        <maven.compiler.source>15</maven.compiler.source>
        <maven.compiler.target>15</maven.compiler.target>
    </properties>

</project>

2. Write a tool class. The function of this class is to call the static method in this class to obtain a SqlSession object (the method returns the SqlSession object)

package com.wt.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;

    //copy官网上的代码创建SqlSessionFactory实例
    static {
    
    
        try {
    
    
            String resource = "mybatis01-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch(IOException e){
    
    
            e.printStackTrace();
        }
    }

    //这个静态的方法返回一个SqlSession实例给调用者,也就是这个工具类的工作
    public static SqlSession getSqlSession(){
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

3. Write the configuration file mybatis01-config.xml needed to create a Factory instance

<?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">
        <!--这个环境用来使用某一用户连接数据库,这里我使用root用户-->
        <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/mybatis?useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--写的mapper一定要在这里注册-->
    <mappers>
        <!--注意注册的路径不是用.而是用/-->
        <mapper resource="com/wt/userDao/UserMapper.xml"/>
    </mappers>
</configuration>

---------------The above preparations are done, and the implementation code will be written below---------------

4. Create entity classes (pojo, also called javabean) based on tables in the database

package com.wt.pojo;

public class User {
    
    
    private int id;
    private String name;
    private String pwd;

    public User() {
    
    
    }

    public User(int id, String name, String pwd) {
    
    
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getPwd() {
    
    
        return pwd;
    }

    public void setPwd(String pwd) {
    
    
        this.pwd = pwd;
    }
}

5. Write the interface of the mapper layer. In mybatis, this interface does not need to be implemented by classes, but needs to be bound to the mapper tag in the configuration file, and the SQL statement that needs to be executed is written in this tag

package com.wt.userDao;

import com.wt.pojo.User;

import java.util.List;

public interface UserDao {
    
    
    List<User> getUserList();
}

6. Write the configuration file that binds the interface in the previous step (also copied from the official document, of course the configuration needs to be modified)

<?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中写出接口的路径-->
<mapper namespace="com.wt.userDao.UserDao">
    <!--id对应接口中的方法,可以看成实现了这个方法-->
    <select id="getUserList" resultType="com.wt.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

7. The above is done, and the rest is executed. Write a test class to test, because the junit package is imported, the test can be very convenient, just execute this method directly.

package com.wt.userDao;

import com.wt.pojo.User;
import com.wt.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    
    
    @Test
    public void test(){
    
    
        //执行sql步骤

        //1、利用工具类获取sqlSession,sqlSession来执行sql语句
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //2、sqlSession对象想要拿到sql,从逻辑上来说就从xml中拿,xml与接口绑定,则要从接口中拿
        //下面就是利用sqlSession的getMapper方法拿到mapper,有了这个mapper,就能执行接口中的方法,执行sql语句了
        UserDao mapper = sqlSession.getMapper(UserDao.class);

        //3、调用方法执行sql语句(一个方法与一个mapper中的某标签绑定,就能执行标签中的sql语句了)
        List<User> userList = mapper.getUserList();

        //这里循环输出结果
        for(User user:userList){
    
    
            System.out.println(user.getName());
        }

        //4、关闭sqlSession
        sqlSession.close();

    }
}

Execution result: The
Insert picture description here
above 7 steps can be used to execute SQL statements using mybatis

Guess you like

Origin blog.csdn.net/kitahiragawa/article/details/112982219