MyBatis-study notes

1. Concept introduction

Concept
MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures and advanced mapping.

  • It maps Java objects and data in the database, enabling Java developers to control SQL statements and mapping relationships through simple XML or annotation configuration, thereby avoiding the tediousness and redundancy of traditional handwritten JDBC codes.

JDBC Disadvantages:
Source: https://www.bilibili.com/video/BV1Qf4y1T7Hx
insert image description here

Mybatis simplified
insert image description here

2. Mybatis quick start

insert image description here

1. Create a user table
drop table if exists tb_user;

create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);



INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');


2. Create module import coordinates
<dependencies>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!-- mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>	

    </dependencies>
3. Write configuration files

insert image description here

<?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>

    <typeAliases>
        <package name="com.itheima.pojo"/>
    </typeAliases>

    <!--
    environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
    -->
    <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:///mybatis_test?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

    </environments>
    <mappers>
        <!--加载sql映射文件-->
        <!-- <mapper resource="com/itheima/mapper/UserMapper.xml"/>-->
        <mapper resource="com/itheima/mapper/UserMapper.xml"/>



    </mappers>


</configuration>
4. Write sql mapping file

https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#Auto-mapping
insert image description here

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--
namespace:名称空间
-->
<mapper namespace="test">
    <select id="selectBlog" resultType="Blog">
        select * from Blog where id = #{
    
    id}
    </select>
</mapper>
5. Coding

Define pojo class (object class), write user class
insert image description here
insert image description here

public class User {
    
    
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

    public Integer getId() {
    
    
        return id;
    }

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

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    public String getGender() {
    
    
        return gender;
    }

    public void setGender(String gender) {
    
    
        this.gender = gender;
    }

    public String getAddr() {
    
    
        return addr;
    }

    public void setAddr(String addr) {
    
    
        this.addr = addr;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

query operation

SqlSessionFactory interface:
used to create SqlSession objects, is one of the key components of MyBatis. It is a thread-safe object that can be reused throughout the life of the application

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--
namespace:名称空间
-->
<mapper namespace="test">
    <select id="selectAll" resultType="user">
        select * from tb_user;
    </select>
</mapper>
import com.itheima.pojo.User;
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;

//快速入门代码
public class MyBatisDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //1.加载核心文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.获取对应的SqlSession对象,用来执行ssql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3.执行sql
        List<User> users = sqlSession.selectList("test.selectAll");

        System.out.println(users);

        //4.释放资源
        sqlSession.close();




    }
}

insert image description here

3.Mapper agent development

Mapper proxy development is a way to simplify database operations in the MyBatis framework. Through dynamic proxy technology, SQL statements are bound to Java interfaces to achieve concise, flexible and type-safe database operations.

  • Solve the hard coding in the native way
  • Simplify post-execution SQL

Mapper Proxy Getting Started Case

  1. Define the Mapper interface with the same name as the SQL mapping file, and place the Mapper interface and the SQL mapping file in the same directory
  2. Set the namespace attribute of the SQL mapping file to the fully qualified name of the Mapper interface
  3. Define the method in the Mapper interface, the method name is the id of the sql statement in the SQL mapping file, and keep the parameter type and return value type consistent
  4. coding
  • Obtain the proxy object of the Mapper interface through the getMapper method of SqISession
  • Call the corresponding method to complete the execution of sql

insert image description here
insert image description here

insert image description here

package com.itheima.pojo;


import com.itheima.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;

public class UserDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    

        //1.加载mybatis的核心配置文件,获取sqlSessionFactory
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.获取SqlSession对象,用它来执行对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3.执行sql
        //3.1 获取用户接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectAll();
        System.out.println(users);

        //4.释放资源
        sqlSession.close();

    }
}

insert image description here

4. MyBatis core configuration file

insert image description here

<?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>

    <typeAliases>
        <package name="com.itheima.pojo"/>
    </typeAliases>

    <!--
    environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
    -->
    <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:///mybatis_test?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

    </environments>
    <mappers>
        <!--加载sql映射文件-->
        <!-- <mapper resource="com/itheima/mapper/UserMapper.xml"/>-->
        <mapper resource="com/itheima/mapper/UserMapper.xml"/>

        <package name = "com.itheima.mapper"/>



    </mappers>


</configuration>
<configurationMyBatis The root element of the core configuration file, which contains the entire configuration information.
<typeAliases Configuration of type aliases, used to alias Java types, simplifying type references in XML configuration and mapping files.
. <package name="com.iheima.pojo"/: Specify a package name, and register all classes under the package as type aliases.
<environments: Configure database connection environment information, you can configure multiple environments
<mappers: Mapper configuration, used to load SQL mapping files or register mapper interfaces.

5. Cases of product addition, deletion, modification and query (key points)

The case completes the addition, deletion, modification and query of brand data;

The JDBC operation is as follows: https://blog.csdn.net/meini32/article/details/131981238

Mybatis operation: https://blog.csdn.net/meini32/article/details/132095237

Annotation operation:

//查询操作
public interface BrandMapper {
    
    
    @Select("select * from tb_brand")
    List<Brand> selectAll();

6. Parameter passing

6.2 Multiple parameters

define interface

  • Use @Param to mark the parameter name, and then write the corresponding one in the mapping file;
  • Use objects to specify parameters
  • Use map to specify parameters
public interface BrandMapper {
    
    

    //使用 @Param 注解来指定参数的名称
    List<Brand> selectByMutiCondition(@Param("status")int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
    
    //使用对象来指定参数
    List<Brand> selectByMutiCondition(Brand brand);  

   //使用map来指定参数
    List<Brand> selectByMutiCondition(HashMap map);
    

}

<!--
namespace:名称空间
-->

<mapper namespace="com.itheima.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

<!--    多条件查询-->
    <select id="selectByMutiCondition" resultMap="brandResultMap">
        SELECT * FROM tb_brand
        WHERE status = #{status} AND company_name LIKE #{companyName} AND brand_name LIKE #{brandName};
    </select>

</mapper>

7. SqlSessionFactory improvement

For the basic operation of Mybatis, there are some repeated codes

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

Having this duplication of code creates some problems:

  • Duplicate code is not conducive to later maintenance
  • SqlSessionFactory factory class for repeated creation
    • It is equivalent to recreating a mobile phone production factory every time you buy a mobile phone to make a mobile phone for you. The resource consumption is very large but the performance is very low. So doing this is not allowed.

optimization

  • Code duplication can extract utility classes
  • Static code blocks can be used to execute the specified code only once
package com.itheima.util;

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

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

/**
 * SqlSessionFactoryUtils 是一个工具类,用于获取 MyBatis 的 SqlSessionFactory 实例。
 */
public class SqlSessionFactoryUtils {
    
    

    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 静态代码块,在类加载时执行,用于初始化 SqlSessionFactory 实例。
     */
    static {
    
    
        InputStream inputStream = null;
        try {
    
    
            // 读取 mybatis-config.xml 配置文件
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        // 使用 SqlSessionFactoryBuilder 构建 SqlSessionFactory 实例
        // 并将其赋值给静态变量 sqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 获取 SqlSessionFactory 实例。
     *
     * @return SqlSessionFactory 实例
     */
    public static SqlSessionFactory getSqlSessionFactory() {
    
    
        return sqlSessionFactory;
    }
}

After the tool class is extracted, it can be used directly when operating the SqlSession of Mybatis in the future

SqlSessionFactory sqlSessionFactory =SqlSessionFactoryUtils.getSqlSessionFactory();

Guess you like

Origin blog.csdn.net/meini32/article/details/132068955