Mr. Cappuccino’s 52nd cup of coffee - Mybatis environment construction and use

Mybatis introduction

Mybatis is a persistence layer framework written in Java language. It uses ORM to encapsulate the result set.
ORM (Object Relational Mapping): Object relational mapping. To put it simply, it corresponds to the database table and the entity class and the attributes of the entity class, so that developers can operate the database table by operating the entity class. It encapsulates many details of the JDBC operation, so that the developer only needs to focus on the SQL statement itself. , without having to pay attention to complex processes such as registering drivers and creating connections.

Mybatis Chinese website

Mybatis environment construction and use

There are two development methods in Mybatis:

  1. Based on annotation method;
  2. Based on XML method;

Generally, the most commonly used way is to develop based on XML, and there are two ways to develop based on XML:

  1. Develop natively
  2. mapper agent development

Based on XML-native way development

  1. Create database tables;
  2. Introduce mybatis related dependencies;
  3. Configure data sources, mybatis and other related configurations (mybatis-config.xml);
  4. Define a Java object, and the member attributes of the object correspond to the field names in the database table;
  5. Define the mapper.xml file to store the SQL statements that need to be executed. Each table corresponds to a mapper;
  6. Call the api in the mybatis framework to execute SQL statements and obtain the result set;
Create database table
CREATE DATABASE IF NOT EXISTS db_mybatis
DEFAULT CHARACTER SET utf8;

USE db_mybatis;

CREATE TABLE `tb_user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
INSERT INTO `tb_user`(`name`) VALUES('Bob');
INSERT INTO `tb_user`(`name`) VALUES('Tom');
INSERT INTO `tb_user`(`name`) VALUES('Jack');
INSERT INTO `tb_user`(`name`) VALUES('John');
Project preparation
Project structure

Insert image description here

Project code

pom.xml

<?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</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
    </dependencies>

</project>

mybatis-config.xml

<?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://127.0.0.1:3306/db_mybatis?serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mappers/userMapper.xml"/>
    </mappers>
</configuration>

UserEntity.java

package com.mybatis.entity;

/**
 * @author honey
 * @date 2023-07-26 15:29:38
 */
public class UserEntity {
    
    

    private Integer id;
    private String name;

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

userMapper.xml

<?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="userMapper">
    <select id="listUser" resultType="com.mybatis.entity.UserEntity">
        select * from tb_user
    </select>
</mapper>

MybatisTest01.java

package com.mybatis.test;

import com.mybatis.entity.UserEntity;
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;
import java.util.List;

/**
 * @author honey
 * @date 2023-07-26 15:26:48
 */
public class MybatisTest01 {
    
    

    public static void main(String[] args) throws IOException {
    
    
        // 1.读取加载mybatis-config.xml(数据源、mybatis等配置)
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2.获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3.根据mapper(namespace="userMapper" + id="listUser")执行sql语句,并将查询到的数据映射成对象(orm)
        List<UserEntity> list = sqlSession.selectList("userMapper.listUser", UserEntity.class);
        System.out.println(list);
        sqlSession.close();
    }
}
Problems caused by adding parameterized constructor methods to entity classes

There is no problem in the following situations

  1. If no constructor is added, the no-parameter constructor will be used by default;
  2. Add no-argument constructor;
  3. Add a parameterized constructor, but the parameters in the constructor match the query result set;

The third case is as follows (the results of the SQL statement query and the parameters in the construction method can be successfully mapped):


SQL statement

Insert image description here

Entity class

Insert image description here


abnormal situation:

  1. The SQL statement remains unchanged. If the entity class is adjusted to the following situation, an error will be reported.

Insert image description here
Insert image description here

  1. The entity class remains unchanged. If the SQL statement is adjusted to the following situation, an error will be reported.

Insert image description here
Insert image description here


Solution: Add an additional no-argument constructor to the entity class.

Insert image description here

Based on XML-mapper agent development

Compared with native development, the advantage of mapper agent development is that it does not rely on literal string values ​​and reduces hard coding.

  1. Define the mapper interface with the same name as the SQL mapping file;
  2. Set the namespace attribute of the SQL mapping file to the fully qualified name of the mapper interface;
  3. The methods in the mapper interface need to be consistent with the ID of the SQL statement in the SQL mapping file;

Develop natively:

List<UserEntity> list = sqlSession.selectList("com.mybatis.mapper.UserMapper.listUser", UserEntity.class);

mapper agent development:

UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<UserEntity> list = mapper.listUser();
Project preparation
Project structure

Insert image description here

Project code

userMapper.xml

<?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.mybatis.mapper.UserMapper">
    <select id="listUser" resultType="com.mybatis.entity.UserEntity">
        select * from tb_user
    </select>
</mapper>

UserMapper.java

package com.mybatis.mapper;

import com.mybatis.entity.UserEntity;

import java.util.List;

/**
 * @author honey
 * @date 2023-07-26 21:04:23
 */
public interface UserMapper {
    
    

    /**
     * 查询用户列表
     *
     * @return List<UserEntity>
     */
    List<UserEntity> listUser();

}

MybatisTest02.java

package com.mybatis.test;

import com.mybatis.entity.UserEntity;
import com.mybatis.mapper.UserMapper;
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;
import java.util.List;

/**
 * @author honey
 * @date 2023-07-26 21:15:48
 */
public class MybatisTest02 {
    
    

    public static void main(String[] args) throws IOException {
    
    
        // 1.读取加载mybatis-config.xml(数据源、mybatis等配置)
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2.获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3.根据mapper(namespace="UserMapper全限定名" + id="listUser")执行sql语句,并将查询到的数据映射成对象(orm)
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<UserEntity> list = mapper.listUser();
        System.out.println(list);
        sqlSession.close();
    }
}
Problem caused by the namespace in the SQL mapping file not being set to the fully qualified name of the interface

If the namespace in the SQL mapping file is not set to the fully qualified name of the interface, the program will not be able to find the SQL mapping file corresponding to namespace = the fully qualified name of the interface during execution.

Insert image description here

Solution:

Insert image description here

Based on annotation

Advantages: XML configuration is removed, which improves development efficiency;
Disadvantages: SQL statements are embedded into Java code. If the SQL statements need to be modified, the source code must be modified, which will increase maintenance costs. XML-based methods are more maintainable;

Project preparation
Project structure

Insert image description here

Project code

pom.xml

<?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</groupId>
    <artifactId>mybatis-annotation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
    </dependencies>

</project>

UserEntity.java

package com.mybatis.entity;

/**
 * @author honey
 * @date 2023-07-26 15:29:38
 */
public class UserEntity {
    
    

    private Integer id;
    private String name;

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

UserMapper.java

package com.mybatis.mapper;

import com.mybatis.entity.UserEntity;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @author honey
 * @date 2023-07-26 21:04:23
 */
public interface UserMapper {
    
    

    /**
     * 基于注解方式查询用户列表
     *
     * @return List<UserEntity>
     */
    @Select("select * from tb_user")
    List<UserEntity> listUserByAnnotation();
}

mybatis-config.xml

<?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://127.0.0.1:3306/db_mybatis?serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.mybatis.mapper.UserMapper"/>
    </mappers>
</configuration>

MybatisTest01.java

package com.mybatis.test;

import com.mybatis.entity.UserEntity;
import com.mybatis.mapper.UserMapper;
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;
import java.util.List;

/**
 * @author honey
 * @date 2023-07-26 21:15:48
 */
public class MybatisTest01 {
    
    

    public static void main(String[] args) throws IOException {
    
    
        // 1.读取加载mybatis-config.xml(数据源、mybatis等配置)
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2.获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3.根据mapper(namespace="com.mybatis.mapper.UserMapper" + id="listUser")执行sql语句,并将查询到的数据映射成对象(orm)
        List<UserEntity> list = sqlSession.selectList("com.mybatis.mapper.UserMapper.listUserByAnnotation", UserEntity.class);
        System.out.println(list);

        // 3.根据mapper(namespace="UserMapper全限定名" + id="listUser")执行sql语句,并将查询到的数据映射成对象(orm)
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<UserEntity> list2 = mapper.listUserByAnnotation();
        System.out.println(list2);
        sqlSession.close();
    }
}

Enterprise-level specification development

There are big disadvantages in using the following two methods of registering mappers.

<mapper resource="mappers/userMapper.xml"/>
<mapper class="com.mybatis.mapper.UserMapper"/>

Disadvantage: Every time you create a mapper interface or mapper.xml file, you need to add new configurations in mybatis-config.xml.

During enterprise-level development, package scanning is usually used to register mapper.

<package name="com.mybatis.mapper"/>
Based on XML-mapper agent development (optimized version)

Optimize based on XML-based mapper agent development:

  1. The SQL mapping file needs to be consistent with the package name structure and file name of the mapper interface.

Insert image description here
Note: Although the file names need to be consistent, the file names are not case-sensitive, which means that naming them userMapper.xml or usermapper.xml is feasible.

  1. Modify mybatis-config.xml and use package scanning to register mapper

Insert image description here

Based on annotation method (optimized version)

Optimize based on the annotation method: you only need to modify mybatis-config.xml and use the package scanning method to register the mapper. (Please refer to the second step above)

Register mapping file (the difference between resource, class, and package)
way to register Register object limitation factor
resource Register a single mapping file Directly load the mapping file, there is no restriction on the package name structure and file name of the mapping file, it is very flexible and less error-prone
class Register a single mapper interface The SQL mapping file needs to be consistent with the package name structure and file name of the mapper interface.
package Register all mapper interfaces under the package name The SQL mapping file needs to be consistent with the package name structure and file name of the mapper interface.

Guess you like

Origin blog.csdn.net/sinat_41888963/article/details/131941894