2021-03-11-MyBatis Quick Start

concept

  • MyBatis is a semi-automatic mapping framework. It is called semi-automatic because it needs to manually match the provided POJO, SQL, and mapping relationship, while Hibernate only needs to provide the POJO and mapping relationship.

Introductory case

Set up the environment

下载地址:
https://github.com/mybatis/mybatis-3/releases
创建项目,导入jar包

The basic composition of Mybatis

1)	SqlSessionFactoryBuilder(构造器),
根据配置信息或代码来生成SqlSessionFactory(工厂接口)
2)	SqlSessionFactory:来生成SqlSession
3)	SqlSession:执行SQL并返回结果
4)	SQLMapper:由一个Java接口和XML(或注解)构成

Build SqlSessionFactory

  • Mapping file:
    Insert picture description here
  • Code:
    Insert picture description here

Build SqlSession

Insert picture description here

  • SqlSession two functions
  1. Get the mapper, let the mapper find the corresponding SQL through the namespace and method name, execute the SQL and return the result
  2. Directly execute SQL and return results through naming information

Mapper

映射器是由Java接口和XML文件(或注解)共同组成的。
作用如下:
1)	定义参数类型
2)	描述SQL语句
3)	定义查询结果和POJO的映射关系
4)	描述缓存


  • Define an interface
    Insert picture description here
  • Define the corresponding mapping file
    Insert picture description here
  • Execute query:
    Insert picture description here

Annotation generated mapper

Insert picture description here

Insert picture description here

life cycle

  • After SqlSessionFactoryBuilder
    creates SqlSessionFactory, its mission is completed
  • SqlSessionFactory
    singleton
  • SqlSession
    closes the session through finally

log4j and tools

1.引入log4j的配置文件,打印日志信息,查看执行的底层细节
2.创建SqlSessionFactoryUtil工具类,提供getSqlSession方法

Go CRUD

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113922800