An article introduction to Mybatis (with mind map)

Article Directory

Three-tier architecture

The three-tier architecture contains three layers:

Interface layer, business logic layer, data access layer

  • Three-tier responsibilities
  1. Interface layer: The main function room accepts user data and displays the processing results of the request. Using the web interface to interact with users, the mobile app is also recognized by Biao Aoshi, the user operates in the app, and the business logic is processed on the server side
  2. Business logic layer: receive the passed data, check the data, calculate the business logic, call the data access layer to get the data
  3. Data access layer: Dealing with the database. It mainly realizes the addition, deletion, modification and checking of data. The data in the database is submitted to the business layer, and the business layer processing transaction data is saved to the database

Three-layer corresponding package:

  • Page layer: controller
  • Business logic into: service package
  • Data access layer: dao package

Interaction of classes in the three layers

User interface layer -> business logic layer -> data access layer (persistence layer) -> database (mysql)

Three-tier corresponding processing framework

Page layer-------servlet----springmvc

Business logic layer------service class-------spring

Data access layer-------dao class---------mybatis

Frame concept

Frame is a template

template:

  1. Stipulates some terms, content
  2. Add your own stuff

The framework is some software, semi-finished software, and some basic functions have been defined. The functions that need to be added to you are complete software. Its basic function room is reusable and upgradeable.

Framework features:

  1. Frameworks are generally not omnipotent and cannot do everything
  2. The framework is effective in a certain field, and one aspect of its specialty. For example, mabatis is strong in database operations, but it cannot do other things.
  3. The frame is a piece of software

mybatis framework definition:

A framework, called ibaatis in the early days, and the code is on github.

mybatis is mybatis SQL Mapper Framework for java (SQL mapping framework)

sql mapper: sql mapping

You can map a row of data in the database table 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

dataaccess object (DAOs): data access, perform additions, deletions, and changes to the database

What functions does mybatis provide:

  1. Provides the ability to create Connection, Statement, and Resulset, without the developer creating these objects
  2. Provides the ability to execute sql statements without you having to execute sql
  3. Provides the ability to loop sql, convert sql results into java objects, and list collections
  4. Provides the ability to close resources without you having to close Connection, Statement, ResultSet

What the developer does is: provide SQL statements

Finally: the developer provides the SQL statement-mybatis handles sql-the developer gets the list collection or java object

Summary "Mybatis is a SQL mapping framework. It provides database operation capabilities and enhanced JDBC. Using mybatis allows developers to concentrate on writing SQL, without worrying about the creation and destruction of Connection, Statement, and ResultSet.

getting Started

Download mybatis

https://github.com/mybatis/mybatis-3/releases

mapper file

<?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.bjpowernode.dao.StudentDao">
    <select id="selectStudents" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student order by id
    </select>
</mapper>
<!--
      select:表示查询操作
      id:你要执行的sql语句的唯一标识,mybatis会使用这个id的值来找到要执行的sql语句
         可以自定义,但是要求你使用接口中的方法名称

      resultTyoe:表示结果类型的,表示sql语句执行后得到的resultSet,遍历这个ResultSet得到的java对象的类型
          值写的名称是全限定名称
-->

<!--
sql映射文件:写sql语句的,mybatis 执行这些sql
       1.指定约束文件
       <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        mybatis-3-mapper.dtd:约束文件的名称,拓展名是dtd的

        2.约束文件的作用:限制,检查当前文件中的标签,属性必须符合mybatis的要求.
        3.mapper 是当前文件的根标签,必须的
         namespace:叫做命名空间,唯一值得,可以是自定义的字符串
                   要求你使用dao接口的全限定名称.
        4.在当前文件中,可以使用特定的标签,表示数据库的特定操作.
        <select>:表示执行查询
        <update>:表示更新数据库的操作,就是<update>标签中,写的是update sql语句
        <insert>:表示插入
        <delete>:表示删除

-->

mybatis file

<?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>
    <!--环境配置:数据库的连接信息
         default值必须和某个environment的id值一样
         告诉mybatis使用哪个数据库的连接信息,也就是访问哪个数据库
    -->
    <environments default="development">
        <!--environments:一个数据库的配置,环境
           id:一个唯一值,自定义的,表示一个环境的名称.
        -->
        <environment id="development">
            <!--
                  transactionManager:mybatis的事务类型
                  type:JDBC(表示使用jdbc中Connection对象commit,rollback做事务处理)
            -->
            <transactionManager type="JDBC"/>
            <!--
                 dataSource:表示数据源,连接数据库的
                 type:表示数据源的类型,POOLED表示使用连接池
            -->
            <dataSource type="POOLED">
                <!--
                    dirver,url,username,password是固定的,不能自己改
                -->
                <!--数据库的驱动类名-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--连接数据库的url字符串-->
                <property name="url" value="jdbc:mysql://localhost:3306/springdb"/>
                <!--访问数据库的用户名称-->
                <property name="username" value="root"/>
                <!--访问数据库的用户密码-->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--sql mapper(sql映射文件)的位置-->
    <mappers>
        <!--一个mapper标签指定一个文件的位置
            从类路径开始的路径信息. (可以有多个)
        -->
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
    </mappers>
</configuration>

<!--
   mybatis的主配置文件:主要定义了数据库的配置信息,sql配置文件的位置

   1.约束文件的说明
   <!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
     mybatis-3-config.dtd:约束文件的名称

   2.configuration
-->

Problem: The xml file is not compiled under target.classes

First check the pom.xml file to see if there is:

 <build>
<resources>
  <resource>
    <directory>src/main/java</directory><!--所在目录-->
    <includes><!--包括目录下面的.properties,.xml文件都会扫描到-->
      <include>**/*.properties</include>
      <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
  </resource>
</resources>
  </build>

Make sure the folder is in this format

[(img-PPd8hj7q-1622708095633)(C:\Users\14505\AppData\Roaming\Typora\typora-user-images\image-20210527110755784.png)]

Operation maven

Insert picture description here
  1. Reconstruction project
Insert picture description here
  1. Clear cache
Insert picture description here
Insert picture description here

Try to run these steps every time, and you won't need it after running successfully.

The final way: if the above are not working, copy directly to the target folder

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-P4I1Qky6-1622708095645)(C:\Users\14505\AppData\Roaming\Typora\typora-user-images\ image-20210527111433829.png)]

mybatis debug log

 <!--控制mybatis全局行为的-->
    <settings>
        <!--设置mybatis输出日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

Introduction of main categories

Resources: a class in mybatis, responsible for reading the main configuration file

InputStream in = Resources.getResourceAsStream("mybatis.xml")

SqlSessionFactoryBuilder: Create sqlSessionFactory object,

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

//Create SqlSessionFactory object

SqlSessionFactory : a heavyweight object, the program takes a long time to create an object and uses more resources. In the entire project, one is enough.

SqlSessionFactory: interface, interface implementation class: DefaultSqlSessionFactory

SqlSessionFactory function: get the SqlSession object.

SqlSession SqlSession = factory.openSession();

openSession() method description:

openSession(): Without parameters, get the SqlSession object of the non-auto commit transaction

openSession(boolean):

openSession(true) Get the SqlSession that automatically commits the transaction

openSession(false) Get the SqlSession of the non-autocommit transaction

SqlSession:

SqlSession interface: defines methods to manipulate data such as seletctOne(), selectList(), insert(), update(), dalete(), commit(), rollback()

The implementation class of the sqlSession interface, DefaultSqlSession,

Usage requirements: The SqlSession object is not thread-safe and needs to be used inside the method. Before executing the sql statement, use openSession() to obtain the SqlSession object. After executing the sql statement, you need to close it and execute SqlSession.close(), so It can be guaranteed that its use is thread-safe.

Dynamic agent condition analysis

List studentList = dao.selectStudents(); call

The dao object, the type is studentDao, and the fully qualified name is: com.bjpowernode.dao.StudentDao. The permission name and namespace are the same

Method name, selectStudents, this method is the id value selectStudents in the mapper file

The return value of dao methods can also determine the method SqlSession method to be called by mybatis

If the return value is a list, the SqlSession.selectList() method is called

If the return value is int, or is not a list, look at the label in the mapper, and the corresponding method of SqlSession will be called

Dynamic proxy of mybatis: Mybatis obtains the information of executing SQL statements according to the method call of Dao. Mybatis creates an implementation class of Dao interface according to your Dao interface, and creates the object of this class, completes the SqlSession call method, access database

Dynamic proxy:

StudentDao dao = SqlSession.getMapper(dao接口.class)获取这个dao接口的对象

Use mybatis dynamic proxy mechanism, use SqlSession.getMapper (dao interface)

getMapper can get the implementation class object corresponding to the dao interface

In-depth understanding of parameters

In the sql statement passed in the mapper file from the java code

parameterType: an attribute in the mapper file. Represents the data type of the parameter of the method in the dao interface. For example, the StudentDao interface is not mandatory

Simple type: In mybatis, the basic parameter type and String type in java are called simple types. To get the value of a parameter of a simple type in the mapper file, use #{any character}

Principle of parameter transfer:

/*
 使用#{}之后,mybatis 执行sql语句是使用的jabc中的PreparedStatement对象
    由mybatis执行以下代码
    1.mybatis创建connection个,PreparedStatement对象
       String SQL = "select id,name,email,age from student where id = ?"
       PrepareStatement pst = new PrepareStatement(sql);
       pst.setInt(1,1001);
    2.执行sql封装为resultType = "com.bjpowernode.domain.Student"这个对象
       ResultSet rs = ps.executeQuery();
       while(rs.next()){
       //从数据库中存储数据,并存储到java对象的属性中
       }
*/

Multiple parameters:

  1. Use @Parm to name parameters

Interface public List selectMulitParam(String name,Integer age)

Use @Param("parameter name") String name

mapper file:

<select>
    select * from student where name = #{myname} or age = #{myage}
</select>

Use object method to pass

 <!--多个参数,使用java对象的属性值,作为参数实际值
           使用对象的语法:#{属性名,javaType=类型名称,jdbcType=数据类型}   很少用
           javaType:指java中的属性数据类型
           jdbcType:在数据库中的数据类型
           例如:#{paramName,javaType = java.lang.String,jdbcType=VARCHAR}

           一般我们使用简化方式:#{属性名},javaType,jdbcType的值mybatis通过反射能够获取.不需要提供

    -->
    <select id="selectMultiObject" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student where id = #{paramName,javaType=java.lang.String,jdbcType=VARCHAR}
                                                 or age = #{paramAge,javaType=java.lang.Integer,jdbcType=INTEGER}
    </select>

简化版
#{paramName}即可

Pass parameters by location (understand)

Map parameter transfer (poor readability, not recommended)

# And $

# : Placeholder : tell mybatis to use the actual parameter value instead. And use the PrepareStatiment object to execute the SQL statement, #{...} instead of the SQL statement?. This is safer and faster

#Result: select id,name,email,age from studetn where id =?

** ∗ ∗ : ∗ ∗ 字 符 串 替 换 ∗ ∗ : 告 诉 m y b a t i s 使 用 **:**字符串替换**:告诉mybatis使用 ∗ ∗:∗∗Character character string for changing∗∗:Advertisement v m Y B A T I S making useThe included "string" replaces the location. Use Statement to connect the sql statement with the content of ${}. It is mainly used to replace table names, column names, and sorting of different columns.

The result of $: select id, name, email, age from studetn where id = 1001

The Statement object is used to execute SQL, which is less efficient than PreparedStatement

When you are sure that the data is safe, you can use $

The difference between # and $ (emphasis):

  1. #: Use? Do placeholders in sql statements, use PreparedStatement to execute sql, high efficiency
  2. #: Can avoid sql injection, more secure
  3. $: does not apply to placeholders, it is a string connection method, using the Statement object to execute SQL, which is inefficient
  4. $: There is a risk of SQL injection and lack of security.
  5. $: can replace table name or column name

Encapsulate mybatis output results

mybatis executed the sql statement and got the java object

resultType result type, refers to the data converted to java objects after the sql statement is executed

Processing method:

  • Mybatis executes the sql statement, and then mybatis calls the parameterless construction method of the class to create the object
  • Mybatis pays the specified column value of the ResultSet to the attribute of the same name
<select id="selectMutiPosotion" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
</select>

Peer JDBC:

ResultSet rs = executeQuery("select id,name,email,age from student");
while(rs.next()){
    Student student = new Student();
    student.setId(rs.getInt("id"));
    ...
}

ResultType

resultType result type, which means that after the SQL statement is executed, the data is converted to a java object, and the java type is arbitrary

The other value of resultType result type, 1. The fully qualified name of the type 2. The alias of the type, for example, the alias of java.lang.Integer is int

Define the alias of a custom type

  1. Defined in the mybatis main configuration file to define aliases
  2. You can use custom aliases in resultType
 <typeAliases>
        <!--
        可以制定一个类型一个自定义别名
        type:自定义类型的全限定名称
        alias:别名(短小,容易定义)
        -->
<!--        <typeAlias type="com.bjpowernode.domain.Student" />-->
<!--        <typeAlias type="com.bjpowernode.vo.ViewStudent" alias="vstu"/>-->
        <!--
        <package> name是包名,这个包中的所有类,类名就是别名(类名不区分大小写)
        -->
        <package name="com.bjpowernode.domain.Student"/>
        <package name="com.bjpowernode.vo.ViewStudent"/>


    </typeAliases>

resultMap: result mapping, specify the corresponding relationship between the column name and the attribute of the java object.

  1. You define which attribute the column value is assigned to
  2. When your column name and attribute name are different, be sure to use resultMap
<resultMap id="studentMap" type="com.bjpowernode.domain.Student">
        <!--列名和java属性之间的关系-->
        <!--主键列,使用id标签
            cloumn:列名
            property:java类型的属性名
        -->
        <id column="id" property="id"/>
        <!--非主键列,使用result-->
        <result column="name" property="name"/>
        <result column="email" property="email"/>
        <result column="age" property="age"/>
    </resultMap>
    <select id="selectAllStudents" resultMap="studentMap">
        select id,name,email,age from student
    </select>

The resultMap can be reused.

Do not use resultMap and resultType together, choose one of the two

Another way to use different attributes of resultType, use as to alias

like query

  1. Prepare "% Zhang%" in advance;
  2. Or prepare "%" #{name} "%" in the mapper file

Dynamic SQL

Dynamic sql: The content of sql changes, and different sql statements can be obtained according to conditions.

Mainly the where part has changed.

The implementation of dynamic sql uses the tags provided by mybatis,

It's conditional

grammar:

​ Part of the SQL statement

Used to contain multiple. When multiple IDs are established, a where keyword will be automatically added, and the redundant and or in the if will be removed.

Loop the array in Java, the list collection, mainly used in the in statement of sql

For example, three students whose student id is 1001, 1002, 1003

select * from student where id in (1001,1002,1003)

collection: indicates the type of method parameters in the interface, if it is an array, use array, if it is a list collection, use list

item: custom variables that represent array and collection members

open: the character at the beginning of the loop

close: the character at the end of the loop

separator: the separator between set members

 <!--foreach使用1-->
    <select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
        select * from student where id  in
         <foreach collection="list" item="myid" open="(" close=")" separator=",">
              #{myid}
         </foreach>
    </select>

 <select id="selectForeachTwo" resultType="com.bjpowernode.domain.Student">
        select * from student where id in
        <foreach collection="list" item ="stu" open="(" close=")" separator=",">
            #{stu.id}
        </foreach>
    </select>

Two corresponding methods

 @Test
    public void testselectStudentForeachOne() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        Student stu = new Student(1001, "张三", "[email protected]", 25);
        List<Integer> list = new ArrayList<>();


        List<Student> student = dao.selectForeachOne(list);
        for (Student student1 : student) {
            System.out.println("foreach---one===" + student1);
        }
    }

    @Test
    public void testselectStudentForeachTwo() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        Student stu = new Student(1001);
        Student stu2 = new Student(1002);
        List<Student> list = new ArrayList<>();
        list.add(stu);
        list.add(stu2);


        List<Student> student = dao.selectForeachTwo(list);
        for (Student student1 : student) {
            System.out.println("foreach---one===" + student1);
        }
    }

The sql code snippet is to reuse some grammar

step:

  1. First sql statement, table name, field, etc.
  2. Just use it

Main configuration file

transactionManager: the way mybatis commits transactions and rolls back transactions

type: the type of transaction processing

  1. JDBC: Indicates that the bottom layer of mybatis is to call the Connection object in JDBC, commit, rollback
  2. MANAGED: Delegate the affairs of mybatis to other containers (a server software, a framework (spring))

DataSource: Represents the data source. In the java system, all data sources that implement the javax.sql.DataSource interface are specified. The data source represents the Connection object

type: Specify the type of data source

POOLED : Use connection pool, mybatis return piece PooledDataSource class

UNPOOLED: Every time you execute a sql statement, first create a connection, execute sql, and then close the connection

mybatis will create an UnPooledDataSource to manage the use of Connection objects

JNDI: java naming and directory service (similar to windows registry)

Property profile of the database

Put the connection information of the database in a separate file. Separate from the main configuration file of mybatis, the purpose is to facilitate modification, storage, and processing of information from multiple databases

Define a property configuration file in the resources directory, xxxx.properties, such as jdbc.properties

In the attribute configuration file, define the data, the format is key=value

key: general use, do multi-level directories

For example: jdbc.mysql.driver, jdbc.driver, mydriver

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql//...

In the main configuration file of mybatis, use the location of the specified file, where the value needs to be used, $(key)

How to specify multiple mapper files

Write multiple tags, write as many as there are

Use package name

All xml files in this package can be loaded into mybatis at once

Requirements for using the package:

  1. The mapper file name needs to be consistent with the interface name and is case sensitive
  2. The mapper file and the dao interface need to be in the same directory

pageHelper

pageHelper is used for data paging

Need to import PageHelper dependency

<!--    PageHelper依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>

Need to be imported into the mybatis framework

<!--配置插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

Instructions:

//加入pageHelper的方法,,分页
        //pageNum:第几页,从1开始
        //pageSize:一页中有多少行数据
        PageHelper.startPage(2,2);

xml files can be loaded into mybatis at one time

Requirements for using the package:

  1. The mapper file name needs to be consistent with the interface name and is case sensitive
  2. The mapper file and the dao interface need to be in the same directory

pageHelper

pageHelper is used for data paging

Need to import PageHelper dependency

<!--    PageHelper依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>

Need to be imported into the mybatis framework

<!--配置插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

Instructions:

//加入pageHelper的方法,,分页
        //pageNum:第几页,从1开始
        //pageSize:一页中有多少行数据
        PageHelper.startPage(2,2);

mind Mapping

Insert picture description here