Create the first MyBatis program

table of Contents

Build table

New father and son project

The parent project imports the jar package

Create a new configuration file to connect to the database

Create a new Mybatis tool class to get sqlsession

New entity class

New interface on Dao layer 

New mapper.xml file

New test class

Error resolution: java.lang.ExceptionInInitializerError

Error reporting and resolution: ibatis.binding.MapperRegistry.getMapper


 

Build table

 

We first build a database and a user table, insert data

 

 

New father and son project

 

The structure is as follows

 

 

The parent project imports the jar package

 

There is nothing to say about importing jar packages. Note that the last two <filter> tags must be false, which is actually very easy to understand. I don't let maven filter out the file path I configured, so set false

<?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.lt</groupId>
    <artifactId>Mybatis-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Mybatis-01</module>
    </modules>

    <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <!--在build中配置resources,防止配置文件编译时失败-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

 

Create a new configuration file to connect to the database

 

This is the configuration file mybatis-config.xml of the project. Don't write the wrong database user name and password

<?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核心配置文件-->
<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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/lt/dao/UserMapper.xml"/>
    </mappers>
</configuration>

Pay attention to our <mapper> tag, where I registered the UserMapper.xml file in mybatis. But if there are multiple xml files, you can use wildcards

<mapper resource="com/lt/dao/*Mapper.xml"/>

 

 

Create a new Mybatis tool class to get sqlsession

 

The use of mybatis needs to pass SqlSessionFactoryBuilder ===》 SqlSessionFactory ==》 SqlSession.

In fact, it is SqlSession that helps us to add, delete, modify and check data.

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

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            //使用Mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
    // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

 

 

New entity class

 

package com.lt.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 String getName() {
        return name;
    }

    public String getPwd() {
        return pwd;
    }

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

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

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

 

 

New interface on Dao layer 

 

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

 

 

New mapper.xml file

 

For writing SQL statements 

<?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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.lt.dao.UserDao">

    <!--select查询语句-->
    <select id="getUserList" resultType="com.lt.pojo.User">
       select * from mybatis.user
   </select>

</mapper>

 

New test class

 

package com.lt.dao;

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

import java.util.List;

public class UserDaoTest {
    @Test
    public void test(){
        //第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();


        //方式一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }



        //关闭SqlSession
        sqlSession.close();
    }
}

 

 

Error resolution: java.lang.ExceptionInInitializerError

 

If you only import dependencies in the pom file, you will get an error if you don't add a build tag at the end. The reason is that maven will not compile custom xml files by default when the program is compiled. So you need to set it in the <build> tag to compile this part of the xml file

 

 

Error reporting and resolution: ibatis.binding.MapperRegistry.getMapper

 

what does this mean? 

This error means that as long as you use the configured mabtis file, you must register the mybatis file in the configuration file of the entire project

 

Published 568 original articles · Like 180 · Visits 180,000+

Guess you like

Origin blog.csdn.net/Delicious_Life/article/details/105627664