02_The first MyBatis program


  1. Set up the environment;
  2. Import the jar package;
  3. Write code;
  4. test.

Project structure:

1. Build an experimental database

CREATE DATABASE `mybatis`;USE `mybatis`;DROP table if exists `user`; create table `user`(`id` int(20) not null,`name` varchar(30) DEFAULT null,`pwd` varchar(30) DEFAULT null,PRIMARY KEY(`id`))ENGINE=INNODB DEFAULT CHARSET=utf8; insert into `user`(`id`,`name`,`pwd`)VALUES(1,'gengsj','123456'),(2,'lisc','123456'),(3,'liwei','54321');

The effect is as follows:

2. Import the jar package related to mybatis

Create a maven project mybatis

Add dependency in parent pom.xml:

<!--    导入依赖-->    <dependencies><!--        1.mybatis-->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.5.3</version>        </dependency><!--        2.mysql-->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>8.0.18</version>        </dependency><!--        3.junit-->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.12</version>            <scope>test</scope>        </dependency>    </dependencies>

3. Write the core configuration file of mybatis


Role: connect to the database

<?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/test?serverTimezone=UTC&amp;characterEncoding=UTF8&amp;useSSL=false"/>                <property name="username" value="root"/>                <property name="password" value="123456"/>            </dataSource>        </environment>    </environments>    <mappers>   <!--     <mapper resource="org/mybatis/example/BlogMapper.xml"/>-->        <mapper resource="com/geng/dao/UserMapp.xml"/>    </mappers></configuration>

4. Write mybatis tool class


package com.geng.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 {    // 该类的目的:获取SqlSession对象    // 第一步:获取SqlSessionFactory对象    public static SqlSessionFactory sqlSessionFactory;    static {        String resource = "mybatis-config.xml";        try {            InputStream inputStream = Resources.getResourceAsStream(resource);            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        } catch (IOException e) {            e.printStackTrace();        }    }    // 第二步:通过SqlSessionFactory获取SqlSession对象    public static SqlSession getSqlSession(){        SqlSession sqlSession = sqlSessionFactory.openSession();        return sqlSession;    }}

Reasons for adding static:

Basic, static keyword:

Usually when defining a class, an object is not actually generated. Only when new will an object be actually generated.

When you want to have only one copy of certain specific data in memory, you can use the  static  keyword

Static can be modified: attributes, methods, code blocks, internal classes

Features after being modified: 1. Load with the loading of the class; 2. You can directly use the class to call without creating an object.

3. Write the code

5. Create an entity class


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;    }     @Override    public String toString() {        return "User{" +                "id=" + id +                ", name='" + name + '\'' +                ", pwd='" + pwd + '\'' +                '}';    }}

Dao interface


Attention is the interface! interface!

package com.geng.dao; import com.geng.pojo.User; import java.util.List; public interface UserDao {    List<User> getUserList();}

Should have written UserDaoImpl.java

package com.geng.dao; import com.geng.pojo.User; import java.util.List; public class UserDaoImpl implements UserDao {    @Override    public List<User> getUserList() {        return null;    }}

Actually edit


<?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.geng.dao.UserDao">    <select id="getUserList" resultType="com.geng.pojo.User">        select * from mybatis.user    </select></mapper>

namespace binding interface, id binding method.

Here the UserMapper.xml icon is gray, renaming can solve the problem.

the reason

Comparison of UserDaoImpl and UserMapper.xml



package com.geng.dao; import com.geng.pojo.User;import com.geng.utils.MybatisUtils;import org.apache.ibatis.session.SqlSession;import org.junit.Test; import java.util.List; public class UserDaoTest {    @Test    public void test1(){        // 第一步:获取SqlSession对象        SqlSession sqlSession = MybatisUtils.getSqlSession();         // 第二步:执行SQL        UserDao userDao = sqlSession.getMapper(UserDao.class);        List<User> userList = userDao.getUserList();         for (User user : userList) {            System.out.println(user);        }         sqlSession.close();    }}

Execution effect:

Problems you may encounter:

1. The configuration file is not registered;

2. Wrong binding interface;

3. The method name is incorrect;

4. The return type is incorrect;

5. Maven export resource problem.

When there is a problem with maven exporting resources, that is, there is no UserMapper.xml in the corresponding location in the target folder, you can add the following content to the pom.xml file:

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

Three interfaces of mybatis

SqlSessionFactoryBuilder: Create SqlSessionFactory

SqlSessionFactory: Create SqlSession


2021.6.5 Shanghai Caohejing