MyBatis basis -ORM, global configuration, mapper configuration, usage

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_40918961/article/details/98782281

table of Contents

 

Basic concepts

SNAKE

MyBatis

MyBatis Functional Architecture

MyBatis framework architecture

MyBatis difference with JDBC, Hibernate's

Basic terms

Basic use

installation

Basic core configuration file

Core Mapper mapping file

Process Overview

1. Import dependence and disposed in pom.xml

2. Configure the master file, and continue to add typeAlias, mapper in the development process, etc.

 

3. Write a mapping that interfaces with the xml mapping file

4. Use the map to complete the implementation of sql statement


Basic concepts

SNAKE

ORM (Object Relational Mapping), i.e., object-relational mapping, it is an object oriented programming language to complete the mapping between database. The only role of ORM tools are: the preservation of persistent objects, modify, or delete operation, the operation translate into the database.

ORM basic mapping relations:

  • Data Class table mapping
  • Data table row mapping object (instance)
  • Column attribute data table (Field) mapping object

MyBatis

MyBatis is excellent persistence framework to support custom SQL, stored procedures and advanced mappings. MyBatis avoids almost all JDBC code and manual setting parameters and the result set retrieved capsule. MyBatis can configure and native Map using simple XML or annotation interface and Java POJO (Plain Old Java Objects, ordinary Java Objects) to database records in.

MyBatis The main idea is to program a large number of SQL statements extracted, configured in the configuration file in order to achieve a flexible configuration of SQL.

MyBatis is not entirely an ORM framework, its design and ORM similar, except that it allows you to write SQL statements directly, make database access more flexible. Therefore, to be precise, MyBatis offers a "semi-automatic" in the ORM achieve a "SQL Mapping" framework.

MyBatis Functional Architecture

Divided into three

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 : is responsible for supporting the most basic functions, including connection management, transaction management, caching configuration and loading, these things are common, they are extracted out as the most basic components, to provide the most basic data processing for the upper layer support.

MyBatis framework architecture

Load configuration : MyBatis application loads the XML configuration file runtime environment, create SqlSessionFactory, SqlSessionFactory can be derived from xml configuration files or annotations, the SQL configuration information is loaded into a one MappedStatement objects (including incoming parameter mapping configuration, SQL execution statements, the results of the mapping configuration), stored in memory.

SQL parsing : when the API interface layer receives the call request, the incoming SQL receives the ID and the incoming object (may be Map, JavaBean or the basic data types), Mybatis find the corresponding SQL according MappedStatement ID, then in accordance with parameter object passed to MappedStatement parsing, SQL statements can be parsed and final parameters to be executed.

SQL execution : SqlSession The resulting SQL database and get the execution parameters, to obtain the results of the database operation.

Results Mapping : The result of the operation in accordance with the database mapping converts configuration, can be converted into HashMap, JavaBean or the basic data types, and returns the final result, after closing SqlSession exhausted.

more specific:

1.SqlSessionFactory

sql session factory, each based on the application of example MyBatis is a SqlSessionFactory as the core. SqlSessionFactory a single database mapping relationship through memory-mapped compiled (similar to JDBC After the driver is loaded, create a connection). Examples can be obtained by SqlSessionFactory SqlSessionFactoryBuilder. And can be constructed SqlSessionFactoryBuilder SqlSessionFactory example XML configuration file from a predetermined or customized instance of Configuration. SqlSessionFactory is created SqlSession factory.

2.SqlSession

SqlSession operation is performed object persistence, which completely contains all the methods required for performing database SQL command, SQL statement can be executed directly mapped SqlSession instance (similar to JDBC acquired Statement / PreparedStatement by the connection, and then perform SQL). After using SqlSession we should use the finally block to ensure close it.

MyBatis difference with JDBC, Hibernate's

        Mybatis also based on JDBC. Java and database operations can only be done through JDBC. Mybatis have complete data queries via JDBC, to update these actions. Mybatis just made, OO technology, transaction management interface package these things in JDBC basis. Mybatis Hibernate and JDBC API are shielding the underlying details of the party asked, so that we are not used to dealing with JDBC API to access the database. However, Hibernate ORM is fully automatic mapping tool that automatically generates SQL statements, Mybatis need to write SQL statements in the xml configuration file; because Hibernate automatically generates SQL statements, when writing complex queries, Hibernate achieve more complex than Mybatis .

Basic terms

The presentation layer (view level), business layer (the business logic), persistence layer (data access layer), Note: strictly speaking persistence layer includes a data access layer

The presentation layer is responsible for receiving a user request, forwarding the request, the display data and the like; service layer is responsible for the organization business logic; persistence layer is responsible for persistent business objects.

The three layered, each layer has a different model, that is architectural pattern. The most common presentation layer architecture model is the MVC

DAL: data access layout data access layer

DAO: data access object data access objects

Basic use

installation

To use MyBatis, just in the project  mybatis-xxxjar  you can import the file.

If you use Maven to build the project, it would take place the following code in pom.xml dependency file:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

(How to use the framework, can be viewed directly Chinese official document: | ------ ------ Portal | )

Basic core configuration file

XML configuration file contains the settings for MyBatis core system, comprising a database connection instance data source (the DataSource) transactional scope and decisions and transaction manager (the TransactionManager) control method. Usually placed under src / main / resources.

Look at an example:

<?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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

Label MyBatis configuration profiles include:

  • configuration configuration
    • properties properties
    • settings settings
    • typeAliases type named
    • typeHandlers type of processor
    • objectFactory object factory
    • plugins plugin
    • environments environment
      • environment Environment Variables
      • transactionManager Transaction Manager
    • databaseIdProvider database vendor identification
    • mapper mappers

 properties properties

This tag is used to declare a name / value, set the variable corresponding to the head, the following configuration can be directly used, to avoid redundancy.

Using the subordinate label property declarations key / value, such as:

<properties>
      <property name="username" value="root"/>
      <property name="password" value="123"/>
</properties>

Url or resource may be used for external configuration and dynamic Alternatively, for example, to establish the Java property file  config.properties , some of the information used to configure the database, as follows:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
username=root
password=xxx

Configuring <properties ... /> attributes in the configuration file can be directly introduced

<properties resource="config.properties"/>

It can then be passed through the sub-element values of the properties in the other element tag, as provided herein  username and  password values:

<dataSource type="POOLED">
     <!--直接拿properties中的值过来用即可-->
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
</dataSource>

If the same name, the priority is such that: attribute parameters passed by the process having the highest priority (i.e., other internal tag custom property the highest priority), resource / url attribute specified in the configuration file, and the lowest priority the properties are specified in the properties of the property.

 settings settings

The tag set some internal operation setting (e.g., automatically generate the primary key, set the timeout, etc.) MyBatis runtime if not specified set default value is used.

For details see the official document: http://www.mybatis.org/mybatis-3/zh/configuration.html#settings

typeAliases type alias 

Type an alias for Java type is set a short name. And only XML configuration related to the meaning of existence is only used to reduce redundancy fully qualified class name. E.g:

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

When such a configuration, Blog can be used anywhere domain.blog.Blog of.

You can also specify a package name, MyBatis will search package name below the required Java Bean, such as:

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

Each package domain.blog in the Java Bean, without comment, it will use the first letter lowercase Bean non-qualified class name as an alias for it. For example domain.blog.Author alias for the author; if the annotation is an alias for the annotation value. See the following example:

@Alias("author")
public class Author {
    ...
}

Here are some common Java types for the corresponding built-in type aliases. They are case-insensitive, note the special naming style for basic types of duplicate names taken.

Aliases Type mappings
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

environments environment

MyBatis actual environment configuration data source is arranged. MyBatis can configure multiple environments, will help you map correspond to a variety of SQL databases. environments environment environment is equivalent to a database connection configuration, you can select only one instance of each SqlSessionFactory environment.

With multiple environments environment, multiple sub-label for each environment

Environments element defines how to configure the environment.

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    </dataSource>
  </environment>
</environments>

Note the key points:

  • ID use the default environment (such as: default = "development").
  • Each environment defined environment ID (such as: id = "development").
  • Transaction manager configuration (for example: type = "JDBC").
  • Configuration data source (for example: type = "POOLED").

The default environment and the environment ID is self-explanatory, so at a glance.

About environment sub-tabs:

    transactionManager Transaction Manager

There are two types of transaction manager with MyBatis (ie type = "[JDBC | MANAGED]"):

  • JDBC - This configuration is the direct use of JDBC commit and rollback is provided, which depends on the connection data obtained from the source to manage transactions scope.
  • MANAGED - This configuration almost did not do. It never commit or roll back a connection, but let the container to manage the entire life cycle of a transaction (such as context JEE application server). By default, it will close the connection, however, some containers do not want this, so you need to closeConnection property to false to prevent its default behavior is closed. E.g:
    <transactionManager type="MANAGED">
      <property name="closeConnection" value="false"/>
    </transactionManager>

If you are using Spring + MyBatis, there is no need to configure the transaction manager, because the Spring module will use its own manager to overwrite the previous configuration.

Both types of transaction managers do not need to set any properties. In fact, they are the type of alias.

    dataSource data source

dataSource element using standard JDBC data source interface configured resource JDBC connection objects. MyBatis three kinds of built-in data source types, i.e., type = "[UNPOOLED | POOLED | JNDI]", which specifies the data source attributes can be configured.

(1) UNPOOLED

UNPOOLED does not support source data JDBC connection pool, but each to achieve open and close the connection when requested. It contains attributes:

  • driver: JDBC driver fully qualified Java class name, such as the MySQL com.mysql.jdbc.Driver
  • url: JDBC URL address database
  • username: User name of the database
  • password: password for the database
  • defaultTransactionIsolationLevel: default connection transaction isolation level.

(2) THE PARTIES

POOLED supports JDBC connection pool data source, using the concept of "pool" will be organized JDBC Connection objects to avoid initialization and certification time when creating a new instance of the connection necessary. In addition there are also attributes include UNPOOLED poolMaximumActiveConnections, poolMaximumIdleConnections attributes.

(3)JNDI

JNDI support external data source connection pool, its implementation is such as to be able to EJB server application or use of such a container, the container may be centralized or configuration data in an external source, and then placed in a JNDI context reference. It contains attributes:

  • initial_context: used to search the context InitialContext
  • data_source: reference paths context data source instance position

mapper mappers

        Data Access Objects DAO defined, data tables set up, and how the data curd operation, that sql does it work? For DAO, to define the appropriate interface, which provides a range of ways of manipulating the DAO (additions and deletions to check what changes ), while setting a xml configuration file corresponding to that interface, the xml configuration corresponding to the obtained DAO mappers tab in the main configuration file.

        To put it plainly is to define the mapping SQL statements. But first we need to tell MyBatis where to find them. Java automatically find in this area does not provide a good way, so the best way is to tell MyBatis where to find the map file. You can use the resource class path relative to a reference, or a fully qualified resource locator (including file: /// of the URL), the class and package names, or the like. E.g:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

These configurations tell MyBatis where to find the map file, and the rest of the details should be mapped for each SQL file

Core Mapper mapping file

When using the JDBC database manipulation write sql, sql to perform manually every time access to data, map file is designed to be placed where the sql statement, sql how to perform corresponding to the DAO? The answer is to use the interface, the interface provides control of DAO a method, implemented sql profile using these methods corresponding to the map, and then configuration (the mapper mappers tag) in the main configuration file, complete decoupling.

That write interface, then write xml configuration file.

Mapping file (mapper) included top-level elements:

  • cache: cache for a given namespace configuration.
  • cache-ref: other namespaces referenced cache configurations.
  • resultMap: Describes how to load from the database result object.
  • sql: reusable statement block can be referenced by other statements.
  • insert: Mapping insert statements
  • update: mapped UPDATE statement.
  • delete: Mapping delete statement
  • select: Mapping query

Properties namespace = "xxx" where xxx must be an interface name, so as to complete the binding

select

select the mapping query, select the query element is very simple and straightforward. such as:

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

select the query to the results are automatically mapped to the type resultType or resultMap specified.

Such as:

<select id="selectUsers" resultType="com.someapp.model.User">
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</select>

select a number of built-in attributes, commonly used is the id, parameterType, resultType, resultMap. If the type is a resultType write their own Java Bean, then MyBatis will automatically create a corresponding resultMap, of course, can also be manually configured resultMap.

resultType:

1, the basic types: resultType = basic types

2, List Type: resultType = Type List elements

3, Map Type resultType = map

Select * i.e. automatically return list, resultType xml = List of elements can type.

resultMap

resultMap equivalent result set, it may be provided outside, the resultType if used, will be automatically configured, if the configuration is more complex, it may be provided outside the resultMap. Attribute is the corresponding column of primary configuration.

<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name"/>
  <result property="password" column="hashed_password"/>
</resultMap>

ResultMap property used in reference to its statement on the line (notice we removed resultType property). such as:

<select id="selectUsers" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>

If it is a complex sql statement, the map will become complicated, resultMap provide multi-seed tag to solve these things.

id: primary key mapping, i.e. DAO fields of the database table primary key mapping

result: non-primary key mapping

id attribute result is the common property (DAO specified fields), column (column designated mapping), (specify the type of field mapping) the javaType

constructor: mapping configuration, if the constructor is defined in DAO, it can be configured accordingly in resultMap

            Example:

public User(Integer id,String username,String password,String sex,String address){
    this.id = id;
    this.username = username;
    this.password = password;
    this.sex = sex;
    this.address = address;
}

Configured to:

<resultMap id="userMap" type="User">
    <constructor>  
        <idArg column="id" javaType="int"/>
        <arg column="username" javaType="String"/>
        <arg column="password" javaType="String"/>
        <arg column="sex" javaType="String"/>
        <arg column="address" javaType="String"/>
    </constructor>  
</resultMap>

You can specify parameters and type.

discriminator: discriminator for discriminating the value of the dynamic and mapped to a corresponding column of the result set, i.e., a value assigned by the column to the DAO different fields, much like Java language switch statements.

update/insert/delete

And select Similarly, what features you want to directly view the official documentation

Process Overview

1. Import dependency and disposed in pom.xml <build>

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>lsl</groupId>
    <artifactId>lsl.desigin.db</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>springJdbc</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
    </dependencies>


    <!--指定执行时的扫描选项-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

 

2. Configure the master file, and continue to add typeAlias, mapper in the development process, etc.

<?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 resource="myBatis.configure.properties" />

    <typeAliases>
        <typeAlias alias="Student" type="dao.Student"  />
        <typeAlias alias="Elder" type="dao.Elder"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="mapper"/>
    </mappers>

</configuration>

 

3. Write a mapping that interfaces with the xml mapping file

package mapper;

import dao.Student;

public interface StudentMapper {
    Student selectStudentById(Integer id) throws Exception;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.StudentMapper">

    <select id="selectStudentById" parameterType="int" resultType="Student">
        select * from students where id=#{id}
    </select>

</mapper>

4. Use the map to complete the implementation of sql statement

Use process:

Resources.getResourceAsStream (configResource) to obtain the total flow profile

new SqlSessionFactoryBuilder () build (resourceInputStream);. The total flow through the plant acquired session configuration file

sqlSessionFactory.openSession (); Open Session

sqlSession.getMapper (StudentMapper.class); obtaining a corresponding interface object is achieved automatically generated by reflection, dynamic proxies, etc.

Student student = studentMapper.selectStudentById (1); sqlSession.commit (); perform sql, submitted to the session

package study;

import dao.Student;
import mapper.StudentMapper;
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;

public class MyBatisStudy {
    private static String configResource="MyBatis.config.xml";
    private static InputStream resourceInputStream=null;

    public static void main(String[] args){
        try {
            resourceInputStream= Resources.getResourceAsStream(configResource);//获取文件配置流
        }catch (Exception e){
            e.printStackTrace();
        }

        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceInputStream);//创建工厂,传入信息
        SqlSession sqlSession=sqlSessionFactory.openSession();//开启会话
        StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);//获取映射1,返回相关实例

        //可以执行sql语句了,对应的映射由MyBatis帮助完成
        try{
            Student student=studentMapper.selectStudentById(1);
            sqlSession.commit();//会话进行提交执行
            System.out.println(student.toString());
        }catch (Exception e){
            e.printStackTrace();
        }

        sqlSession.close();//关闭会话即可
    }
}

 

Guess you like

Origin blog.csdn.net/qq_40918961/article/details/98782281