Mybatis(1)---Frame overview, the first Mybatis

1. Framework overview

1.1 MyBatis

MyBatis is equivalent to an enhanced version of JDBC

1.2 Commonly used architectures for software development

Three-tier architecture
Interface layer (view layer): receives user data and displays the processing results of the request (html, jsp, servlet, etc.)
Business logic layer: receives data from the interface layer, checks the data, and calls the data access layer to obtain the
data Access layer (persistence layer): complete database operations (addition, deletion, modification, and check)

Three-layer corresponding package:
interface layer: controller package (servlet)
business logic layer: service package
data access layer: dao package

Three-tier interaction

Interface layer->Business logic layer->Data access layer->Database

Three-tier corresponding processing framework

Interface layer—
servlet —SpringMVC framework Business logic layer—service class—Spring framework
Data access layer—dao class—mybatis framework

1.3 What is the framework?

The frame is a stage and a template (resume, insurance policy, etc.)

Some terms and content have been stipulated in the template, fill in your own things

Some functions are defined in the framework and can be added to the functions in the project. These functions can use the functions written in the framework

The framework is similar to a semi-finished software. Some basic functions have been defined in this software. Just add the required functions. These basic functions are reusable and upgradeable.

1.4 Characteristics of the framework

1) Frameworks are generally not omnipotent and cannot do everything

2) The framework is only effective for a certain field. For example, mybatis only targets database operations

1.5 JDBC defects

Lots of code, low efficiency

Duplicate code

Need to realize the creation and destruction of Connection, Statement, ResultSet objects

Business code and database operations are mixed

1.6 Overview of mybatis

Mybatis was called ibatis in the early days, which was a sql mapping framework

1) sql mapper: sql mapping

A row of data in a database table can be mapped to a Java object. A
row of data can be regarded as a Java object. Operating this object is equivalent to operating the data in the table.

2) data access object (DAO): data access, add, delete, modify, and check the database

1.7 The function of mybatis

1) Provides the ability to create Connection, Statement and ResultSet

2) Provides the ability to execute sql statements

3) Provides the ability to loop sql and convert the result of the sql statement into a Java object (List collection)

4) Provides the ability to shut down resources

Developers need to provide sql statements-mybatis to process sql- developers to get List collection or java objects

1.8 Summary

Mybatis is a sql mapping framework that provides database operation capabilities and is an enhanced JDBC. Use mybatis to allow developers to write only sql statements, without worrying about the creation and destruction of Connection, Statement, ResultSet and the execution of sql statements

Two, Mybatis use steps

2.1 Create the first mybatis

step

(1) Create a new table and insert data

CREATE TABLE `t_test` (
  `id` int NOT NULL,
  `name` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Data in the table:
Insert picture description here

(2) Add Maven's Mybatis coordinates and MySQL-driven coordinates in the pom.xml file

<!--加入mybatis依赖-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<!--加入MySQL驱动依赖-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.19</version>
</dependency>
</dependencies>

(3) Create an entity class Test to save a row of data in the table

//用于保存t_test表中一列数据的类
public class Test
{
    
    
    private Integer id;
    private String name;

    public Integer getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

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

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

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

(4) Create the DAO interface of the persistence layer and define the method of operating the database

import java.util.List;

//定义操作test表的接口
public interface TestDao
{
    
    
    //查询test表中所有数据的方法
    public List<Test> selectTests();
}

(5) Create the configuration file used by Mybatis, the sql mapping file, which is used to write SQL statements. Generally, there is one sql mapping file per table. The suffix of
this file is .xml. This file is written in the directory where the DAO interface is located, the name of the file Consistent with the interface

<?xml version="1.0" encoding="UTF-8" ?>
<!--
    当前文件为sql映射文件
    可以在里面编写sql语句
-->
<!--
    1.指定约束文件
        mybatis-3-mapper.dtd是约束文件名称,扩展名是dtd的
    2.约束文件的作用
        限制,检查当前文件中出现的标签和属性是否满足mybatis规范
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
    3.mapper:当前文件的根标签,是必须值
    4.namespace:命名空间的,是唯一值,可以自定义标签的字符串,要求使用dao的全限定名称
-->
<mapper namespace="HelloMybatis.TestDao">
    <!--
        5.当前文件中,可以使用特定的标签,表示数据库的特定操作
        <select>表示查询,里面放的是select语句
        <update>表示更新数据库的操作:写update语句
        <insert>表示插入操作,写insert语句
        <delete>表示删除,执行的是delete语句
    -->
    <!--
        select:表示查询操作
        id:要执行的sql语句的唯一标识,mybatis会使用这个id的值找到要执行的sql语句
        这个id可以自定义,但要求使用接口中的方法名称
        resultType:遍历sql语句执行后得到的ResultSet之后得到的Java对象的类型
        值写的是类型的全限定名称
    -->
    <select id="selectTests" resultType="HelloMybatis.Test">
        select * from t_test ORDER BY id;
    </select>
</mapper>

(6) Create the main configuration file of mybatis, there is only one in a project, the main configuration file provides the connection information in the database and the location information of the sql mapping file

<?xml version="1.0" encoding="UTF-8" ?>
<!--
    当前文件为mybatis的主配置文件
    主要定义了数据库的配置信息,sql映射文件的位置等
-->
<!--
    1.约束文件名称:mybatis-3-config.dtd
-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--
    2.configuration:根标签
-->
<configuration>
    <!--
        3.环境配置:数据库的连接信息
        default的值必须和某个environment的id相同,告诉mybatis要使用哪个数据库的信息
        即要访问哪个数据库
    -->
    <environments default="development">
        <!--
            4.environment:一个数据库信息的配置
            5.id:一个自定义的唯一值,用于表示环境的名称
        -->
        <environment id="development">
            <!--
                6.transactionManager:mybatis的事务类型
                type:JDBC(表示使用jdbc中Connection对象的commit,rollback做事务处理)
            -->
            <transactionManager type="JDBC"/>
            <!--
                7.dataSource:表示数据源,用于连接数据库的
                type:用于表示数据源的类型
                    POOLED:表示使用连接池的
            -->
            <dataSource type="POOLED">
                <!--
                    8.driver,url,username,password是固定的,不能自定义
                -->
                <!--数据库的驱动类名-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <!--连接数据库的url字符串-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatistest?serverTimezone=UTC&amp;useSSL=false&amp;allowPublicKeyRetrieval=true"/>
                <!--访问数据库的用户名-->
                <property name="username" value="root"/>
                <!--密码-->
                <property name="password" value="123456ac"/>
            </dataSource>
        </environment>
    </environments>
    <!--
        9.用于指定sql映射文件(sql mapper)的位置
    -->
    <mappers>
        <!--
            一个mapper标签指定一个文件的位置
            从类路径开始的路径信息:位于target/classes(类路径)之后的路径
        -->
        <mapper resource="HelloMybatis/TestDao.xml"/>
    </mappers>
</configuration>

(7) Create a class that uses mybatis, and access the database through mybatis

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.InputStream;
import java.util.List;

public class MyApp
{
    
    
    public static void main(String[] args) throws Exception
    {
    
    
        //访问mybatis读取t_test中的数据
        //1.定义mybatis主配置文件的名称,从类路径的根开始(target/classes之后的)
        String config = "mybatis.xml";
        //2.读取这个config表示的文件
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4.创建SqlSessionFactory对象
        SqlSessionFactory factory = builder.build(in);
        //5.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //6.指定要执行的sql语句的标识
        //sql映射文件中的namespace+"."+标签的id值
        String sqlId = "HelloMybatis.TestDao" + "." + "selectTests";
        //7.执行sql语句,通过sqlId找到语句
        List<Test> testList = sqlSession.selectList(sqlId);
        //8.输出结果
        testList.forEach(test -> System.out.println(test));
        //9.关闭sqlSession对象
        sqlSession.close();
    }
}

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114456669