How should the most popular Mybatis framework be built?

Do you know the most popular Mybatis framework? How to build it?

MyBatis was originally an open source project iBatis of apache. In 2010, this project was migrated from apache software foundation to google code and renamed MyBatis. Migrated to Github in November 2013.

The term iBATIS comes from the combination of "internet" and "abatis" and is a Java-based persistence layer framework . The persistence layer framework provided by iBATIS includes SQL Maps and Data Access Objects (DAO)

MyBatis is an excellent persistence layer framework that supports ordinary SQL queries, stored procedures and advanced mapping . MyBatis eliminates almost all manual settings of JDBC code and parameters and retrieval and packaging of result sets. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java POJOs (Plain Old Java Objects) into records in the database .

Mybatis is not a complete ORM framework. Mybatis requires programmers to write sql by themselves, but there are also mappings (input parameter mapping, output result mapping). The learning threshold of mybatis is lower than hibernate; at the same time, it has high flexibility and is especially suitable for business models that are changeable. The project has a wide range of use .

Brief summary: **Simplify the jdbc code, simplify the persistence layer, separate the sql statement from the code, and use reflection to map the data in the table to the java bean properties one by one, namely ORM (Object Relational Mapping) **

Use range:

In daily development projects, such as small and medium-sized projects, such as ERP (Crm customer relationship management system, OA system), Hibernate is recommended for relatively fixed requirements and relationship models. For projects with unfixed requirements, such as Internet projects, mybatis is recommended , Because you need to be flexible to write SQL statements often . In short, mybatis has become a persistent layer framework that must be learned and mastered.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-dTuSA9mW-1608280132024)(https://imgkr.cn-bj.ufileos.com/63b1bf51-5d8f-4ee0 -954a-7210cb5a1943.png)]

How to build the Mybatis framework

  • New Maven project
  • log4j log addition
  • Add configuration files in the resources directory
  • Mapping file added
  • Entity class Customer added
  • Get resources in the parent project pom
  • test

Case practice

1. Create a new Maven project

**Create a new maven project, add dependent jar to the pom file **

<!-- mybatis jar 包依赖 -->
<dependency>   
    <groupId>org.mybatis</groupId> 
    <artifactId>mybatis</artifactId>   
    <version>3.4.1</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>   
    <groupId>mysql</groupId> 
    <artifactId>mysql-connector-java</artifactId> 
    <version>5.1.39</version>
</dependency>
<!-- log4j日志打印 -->
<dependency>    
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>  
    <version>1.2.16</version>
</dependency>

2.log4j log addition

Add the log4j log output properties file under the src/main/resources resource package for easy viewing of log output information

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
#Consoleoutput...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3. Add configuration files under the resources directory

Create a new mybatis.xml file and add the configuration information as follows (database name mybatis, table user)

<?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="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring-test" />
                <property name="username" value="root" />
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!-- mapper 配置文件指定 文件数量可配置多个-->
    <mappers>
        <mapper resource="com/xxx/mapper/CustomerMapper.xml" />
    </mappers>
</configuration>

There may not be an automatic prompt for label configuration:

Solution: import mybatis-3-config.dtd file

Window-preferences-Search xml-xml catalog

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-7wV2kMJG-1608280132029) (https://imgkr.cn-bj.ufileos.com/5ae242b8-c51d-41e3) -a3ac-7b6b1897a245.png)]

Add-> in the User Specified Entries directory

Locattion: http://mybatis.org/dtd/mybatis-3-mapper.dtd (the value corresponds to the xml template)
Key Type:URI
Key:-//mybatis.org//DTD Mapper 3.0//EN (the value is Corresponding in the xml template)
Step 2:
Close the xml and reopen it. If it cannot be reopened, just restart Eclipse.

Finally click OK

4. Add mapping file

Create a new CustomerMapper.xml configuration 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">
<!-- 
  1.命名空间配置  全局唯一  包名+文件名
  2.配置Mapped Statement 
  3. statement配置 
       id 值声明statement编号  同一命名空间(同一文件)下不可重复
       parameterType  输入参数即占位符的数据类型  类型可以是 基本数据类型,字符串,java bean ,map,list等
       resultType     输出结果  类型可以是基本数据类型,字符串,java bean,map等
       statement 描述 即待执行的sql  
       #{id}  占位符  变量名为id/value 均可   ${value}  变量名必须为value 字符串拼接形式  无法避免sql 注入    
 -->
<mapper namespace="com.xxx.mapper.customerMapper">
    <!-- 查询客户-->
    <select id="queryCustomerById" parameterType="int" resultType="com.xxx.pojo.Customer">
      SELECT id,user_name 'userName',user_balance 'userBalance' FROM  yg_customer WHERE  id=#{id}
    </select>
</mapper>

5. Add entity class Customer

package com.xxx.pojo;

public class Customer {
    
    
    private  int id;
    private  String userName;
    private  String userBalance;

    public int getId() {
    
    
        return id;
    }

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

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }

    public String getUserBalance() {
    
    
        return userBalance;
    }

    public void setUserBalance(String userBalance) {
    
    
        this.userBalance = userBalance;
    }

    @Override
    public String toString() {
    
    
        return "Customer{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userBalance='" + userBalance + '\'' +
                '}';
    }
}

6. Get resources in the parent project pom

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

7. Test

@Test
public void test() throws IOException {
    
       
    /**       
    a)、读取mybatis的配置文件    
    b)、加载配置文件创建SqlSessionFactory     
    c)、根据SqlSessionFactory创建SqlSession   
    d)、通过sqlSession操作数据库      
    e)、处理结果    
    f)、关闭session   
    */       
    /**    
    * 加载配置到内存 
    */   
    InputStream is= Resources.getResourceAsStream("mybatis.xml");    
    /**  
    *  创建SqlSessionFactory 对象  hibernate 也是如此 必须先获取SqlSessionFactory 实例化对象    	  */    
    SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);    
    /**     
    *  获取session以便操作数据库  
    *  参数一:指定UserMapper.xml 映射文件id  必须加入命名空间     
    *  参数二: 指定输入参数    
    */    
    SqlSession session=factory.openSession();   
    Customer customer = session.selectOne("com.xxx.mapper.customerMapper.queryCustomerById", 2);
    /**    
    * 将返回的结果输出    
    */   
       System.out.println(customer); 
    /**   
    * 操作完数据库 关闭session    
    */  
    session.close();
} 

Expand

MyBatis framework architecture

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-B8pRZQiT-1608280132053)(https://imgkr.cn-bj.ufileos.com/71894e06-f527-4e91 -ae25-8a5cac546481.png)]

Description:

1 Configuration-mybatis configuration

1) Like spring, it can be configured in the form of configuration files or annotations;

2), mybatis.xml, this file is used as the global configuration file of mybatis, which configures the operating environment of mybatis and other information ;

3) The mapper file is the sql mapping file, and the sql statement for operating the database is configured in the file. This file needs to be loaded in mybatis.xml .

4) After having the configuration file, construct the SqlSessionFactory that is the session factory through configuration information such as the mybatis environment

5) sqlSession is a session created by the session factory , and the database needs to be operated through sqlSession

6) sqlSession uses Executor (database operation executor interface) to operate the database, and the specific implementation class of Executor implements the specified dao layer data access operation.

2 Mapped Statement

The bottom layer of the framework encapsulates objects (sql statement, input parameter, output result type), which encapsulates mybatis configuration information and sql mapping information, etc. One sql in the mapper file (ie Mapper.xml) corresponds to a Mapped Statement object, and the sql id is The id of the mapped statement.

3 Sql input mapping parameters

Basic and simple types, HashMap, custom POJO, etc. Input parameter mapping is the setting of parameters for preparedStatement in jdbc programming. Executor maps the input java objects to sql through Mapped Statement before executing sql.

4 Sql output mapping parameters

Basic and simple types, HashMap, custom POJO. Statement defines the sql execution output result. The output result mapping process is equivalent to the analytical processing process of the result in jdbc programming. Executor maps the output result to a java object after executing sql through the Mapped Statement.

The Maven project is used here, and the corresponding mybatis jar package is downloaded through the unified management and download of the maven warehouse.
Insert picture description here

Guess you like

Origin blog.csdn.net/xyx12321/article/details/111380402