In-depth understanding of JAVA MyBatis framework (1)

This article is based on Mybatis explanation, Welcome to learn and progress together.

About a .MyBatis

MyBatis apache this is an open source project iBatis, 2010 Nian migration project by the apache software foundation to google code, and changed its name to MyBatis. Migration in November 2013 to Github.
iBATIS comes from the word "internet" and "abatis" combination, it is a Java-based persistence framework. iBATIS persistence framework include SQL Maps and Data Access Objects (sDAO)

  • MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis avoids almost all JDBC code and manual setting parameters and obtaining the result set. MyBatis can use simple XML or annotation to configure and map the native information, interfaces and Java POJOs (Plain Old Java Objects, ordinary Java Objects) to database records in.

II. Framework Features

  • ① easy to learn : itself is small and simple. Do not rely on any third party, as long as the easiest to install two jar files + configure several sql mapping file is easy to learn, easy to use, through documentation and source code, you can compare fully grasp its design and implementation.
  • ② flexible : mybatis does not impose any impact on the existing application or database design. sql written in xml, to facilitate unified management and optimization. Sql can basically realize we do not use data access framework that can be achieved by all the features, perhaps more.
  • ③ release coupling sql program code : providing the DAL by the data access logic and business logic separated from the system design more clearly, easier to maintain, easier unit testing. sql and the code, which enhances maintainability.
  • ④ provide a mapping label , field support orm object-relational mapping database
  • ⑤ label provides object-relational mapping , support for object-relational form maintenance
  • ⑥ provide xml tags , support the development of dynamic sql

III. The overall process

  • 加载配置并初始化
  • Trigger conditions : load configuration file
  • Process : the SQL configuration information is loaded into a one MappedStatement objects (including incoming parameter mapping configuration, execute SQL statements, the results of the mapping configuration), stored in memory.
  • 接收调用请求
  • Trigger conditions : calling API Mybatis provided
  • Incoming parameters : the SQL ID and incoming parameter object
  • Processing of : transmitting a request for processing to the lower layer of the processing request.
  • 处理操作请求
  • Trigger conditions : API request is transmitted over the interface layer
  • Incoming parameters : the SQL ID and incoming parameter object
  • Process :
  • (A) The search for a corresponding target MappedStatement SQL's ID.
  • (B) from the passed parameter object parsing MappedStatement object parameters to obtain the final pass and execute SQL to be executed.
  • © database connection, according to the final execution of SQL statements and get the parameters passed to the database to perform and get the results.
  • (D) based on the results of the mapping configuration MappedStatement object execution result obtained in the conversion process, and to give the final processing result.
  • (E) to release connection resources.
  • 返回处理结果将最终的处理结果返回

IV. Functional Architecture

  • Mybatis functional architecture is divided into three layers:
  • API interface layer : API provides an interface to external use, by the developer to manipulate these local database API. An interface layer receiving the call request will call the data processing layer to accomplish their data processing.
  • Data processing layer : responsible for specific SQL lookup, SQL parsing, SQL execution and implementation of the results of the mapping process and so on. Its main purpose is to complete the operation at the request of a database call.
  • Base support layer : responsible for the most basic functions of support, including connection management, transaction management, load and configure caching, these are common things that will draw them out as the most basic components. Most basic support for the upper layer data processing.

Here Insert Picture Description

V. Architecture

  • mybatis profile, a global profile, and comprising Mybatis Mybatis mapping file, wherein the global profile configuration information of the data source, and other transaction; mapping file configuration information related to execution of the SQL.
  • ①mybatis by reading the profile information (global configuration file and map file), a SqlSessionFactory constructed, i.e. session factory.
  • ② by SqlSessionFactory, you can create SqlSession That session. Mybatis database is operated by SqlSession.
  • ③SqlSession itself can not directly manipulate the database, the database which is operated by the actuator Executor underlying interfaces. There are two Executor interface implementation class, it is a common actuator, an actuator is a buffer (default).
  • SQL executor ④Executor information to be processed is encapsulated in a MappedStatement underlying object. The object comprises: SQL statement input parameters mapping information, and outputs the result set mapping information. Wherein the input parameters and output results of the mapping of java types include simple types, HashMap collection object, POJO object type.
    Here Insert Picture Description

Six .MyBatis data and interactive way

  • MyBatis and database interaction are two main ways:
  • ① using API conventional MyBatis provided;
  • By calling MyBatis in SqlSession object's methods to achieve and the way interact with the database, there are some similar DBUtils of operation!

Here Insert Picture Description

  • 上述使用MyBatis的方法,是创建一个和数据库打交道的SqlSession对象,然后根据Statement Id和参数来操作数据库This is certainly very simple and practical way, but 它不符合面向对象语言的概念和面向接口编程的编程习惯。because the interface-oriented programming object-oriented trend, MyBatis order to adapt to this trend, the second increase in the use MyBatis Support Interface (Interface) is called.

  • ② use Mapper interfaces;
  • MyBatis each node in the abstract core configuration file for a Mapper interface, this method declared in the interface and with node <select | update | delete | insert> corresponding node items, namely <select | update | delete | insert > Mapper node id is the name of the interface method, the parameter value indicates the type of the parameterType Mapper corresponding method, and the value corresponding to the Mapper resultMap return type or return a result set element represented by the interface type.

Here Insert Picture Description

  • Summary : MyBatis references Mapper interface to call this way, simply to meet the needs of interface-oriented programming. (In fact, there is a reason that the interface-oriented programming, so that the user can use the notes on the interface to configure SQL statements, so that you can out of the XML configuration file, and "0 configuration")

Seven .MyBatis profile

  • 1. The core profile
  • In the classpath, create SqlMapConfig.xml file, which is the core configuration file, you can configure the current environmental information, load the mapping file, load the properties file, configure the global parameters, defined aliases.
<?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>
    <!-- 加载properties文件
    先加载property子标签的内容,后加载properties文件
    如果名称相同,后边覆盖前边内容
    -->
    <properties resource="jdbc.properties">
        <property name="jdbc.password" value="12345"/>
    </properties>
    <!-- 全局参数配置:二级缓存,延迟加载
    <settings></settings>
    -->
    <!-- 定义别名 -->
    <typeAliases>
        <!-- 给单个的类起别名
        <typeAlias type="com.qf.domain.User" alias="user"/>
        -->
        <!-- 给指定包下的类起别名
        别名的定义规则:类名首字母小写
        -->
        <package name="com.qf.domain"/>
    </typeAliases>
    <!-- 配置mybatis的环境信息 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置JDBC事务控制,由mybatis进行管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源,采用mybatis连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 加载映射文件 -->
    <mappers>
        <!-- 使用资源的路径 -->
        <mapper resource="User.xml"/>
        <!-- <mapper resource="com/qf/mapper/UserMapper.xml"/> -->
        <!-- 使用资源的绝对路径<mapper url=""/> -->
        <!--
        Mapper接口的全类名
        要求:Mapper接口的名称与映射文件名称一致
        1.8.2 映射文件
        在指定的目录下创建映射文件,配置要执行的statement,即增删改查等语句。
        必须在同一个目录下
          <mapper class="com.qf.mapper.UserMapper"/>
        -->
        <!-- 加载某个包下的映射文件 (推荐)
        要求:Mapper接口的名称与映射文件名称一致
        必须在同一个目录下
        -->
        <package name="com.qf.mapper"/>
    </mappers>
</configuration>
  • 2. mapping file
  • Created in the specified directory map files, configuration statement to be executed, that is, CRUD and other statements.
<?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">
        <!--
             namespace:配置名称空间,对配置的statement进行分类管理
             此时名称可以任意
             当使用Mapper代理时,namespace具有特殊的含义与功能
      -->
        <mapper namespace="test">
        <!--
            根据id查询用户,User findById(int id)
            select:配置查询语句
            id:可以通过id找到执行的statement,statement唯一标识
            parameterType:输入参数类型
            resultType:输出结果类型
            #{}:相当于占位符
            #{id}:其中的id可以表示输入参数的名称,如果是简单类型名称可以任意
         -->
        <select id="findById" parameterType="int" resultType="com.qf.domain.User" >
        select * from user where id=#{id}
        </select>
        <!--
            根据用户名称来模糊查询用户信息列表;
            ${}:表示拼接sql语句
            ${value}:表示输入参数的名称,如果参数是简单类型,参数名称必须是value
-->
        <select id="findByUsername" parameterType="java.lang.String"
        resultType="com.qf.domain.User">
        select * from user where username like '%${value}%'
        </select>
        <!-- 添加用户
            #{username}:名称与类中的属性名一致
             -->
         <insert id="addUser" parameterType="com.qf.domain.User">
        <!--
             selectKey:查询主键
             keyProperty:主键对应的属性名称
             resultType:结果类型,主键的类型
             order:在插入记录的之前或之后查询主键的值
             select last_insert_id()
             mysql提供 的函数,与insert语句搭配使用,查询主键
      -->
        <selectKey keyProperty="id" resultType="int" order="AFTER">
        select last_insert_id()
        </selectKey>
        insert into user(username,sex,birthday,address)
        values(#{username},#{sex},#{birthday},#{address})
         </insert>
        <!-- 删除用户 -->
         <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
         </delete>
         <!-- 修改用户 -->
         <update id="updateUser" parameterType="com.qf.domain.User">
        update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#
        {address}
        where id= #{id}
         </update>
        </mapper>

  • The best investment is in yourself.

Here Insert Picture Description

  • 2020.03.21 记录辰兮的第34篇博客
Published 37 original articles · won praise 145 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_45393094/article/details/105009080