The basic implementation process of MyBatis

Introduction to MyBaties

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping.

MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets

MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and JavaPOJOs (Plain Old Java Objects) into records in the database

MyBatis history

Originally an open source project of Apache, iBatis, this project was migrated from the Apache Software Foundation to Google Code in June 2010. As the development team switched to Google Code, iBatis 3.x was officially renamed MyBatis, and the code was in November 2013

Migrate to the Github download address .

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

Why use MyBatis

MyBatis is a semi-automated persistence layer framework

• JDBC

JDBC -> Dbutils(QueryRunner) -> JdbcTemplate:工具

Simple function; sql statement is written in java code; hard-coded high coupling method

 

Hibernate: Fully automatic full mapping ORM (Object Relation Mapping) framework; aims to eliminate sql, HQL

Hope: The sql statement is written by our developers, and I hope that sql will not lose its flexibility;

– SQL is trapped in a Java code block, and the high degree of coupling leads to hard-coded internal injuries

– It is not easy to maintain and the actual development requirements of SQL are changed. Frequent modifications are common. • Hibernate and JPA

– Long and complex SQL is not easy to handle for Hibernate

– It is not easy to make special optimizations for SQL automatically produced internally.

– Based on the fully automatic framework of full mapping, it is difficult to perform partial mapping of POJOs with a large number of fields.

Cause the performance of the database to degrade.

• For developers, core SQL still needs to be optimized by itself

Separate sql and java coding, clear functional boundaries, one focused on business and the other focused on data

MyBatis-HelloWorld

The main steps

HelloWorld Simple Edition-Create a test sheet

-Create the corresponding javaBean

-Create mybatis configuration file, sql mapping file

-Test

First create an Employee table in the database and insert a piece of data for testing

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(255) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Guide package in idea

Create the corresponding javaBean object and rewrite the toString method to facilitate subsequent output

public class Employee {
    private int id;
    private String last_name;
    private String gender;
    private String email;

    public Employee() {
    }

    public Employee(int id, String laseName, String gender, String email) {
        this.id = id;
        this.last_name = laseName;
        this.gender = gender;
        this.email = email;
    }

    public int getId() {
        return id;
    }

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

    public String getLaseName() {
        return last_name;
    }

    public void setLaseName(String laseName) {
        this.last_name = laseName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", laseName='" + last_name + '\'' +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

Create Mapper interface

import school.xauat.mybatis.bean.Employee;

public interface EmployeeMapper {

    public Employee getEmpById(Integer id);
}

Create MyBatis global configuration file

– The global configuration file of MyBatis contains settings and properties that deeply affect the behavior of MyBatis, such as database connection pool information. Guide MyBatis to work. We can refer to the configuration example of the official document.

<?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://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="***"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="EmployeeMapper.xml"/>
    </mappers>
</configuration>

Create SQL mapping file

– The role of the mapping file is equivalent to defining how the implementation class of the Dao interface works. This is also the most document we write when using MyBatis.

<?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="school.xauat.mybatis.dao.EmployeeMapper">
    <!--
    namespace:名称空间;指定为接口的全类名
    id:唯一标识
    resultType:返回值类型
    #{id}:从传递过来的参数中取出id值
    -->
    <select id="getEmpById" resultType="school.xauat.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id}
    </select>
</mapper>

test

1. Use SqlSessionFactoryBuilder to create SqlSessionFactory objects according to the global configuration file

/**
     * 获取SqlSessionFactory对象
     * @return
     * @throws IOException
     */
    public static SqlSessionFactory getSqlSessionFactory() throws IOException{
        String resource = "mybatis-config.xml";
        InputStream  inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

2. Use SqlSessionFactory to obtain the SqlSession object, a SqlSession object represents a session with the database

public static void test01() throws IOException {
        //1、获取SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //2、获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3、获取接口的实现类对象
        //会为接口自动创建一个代理对象,代理对象去执行增删改查
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = mapper.getEmpById(1);
        System.out.println(mapper.getClass());
        System.out.println(employee);
        sqlSession.close();
    }

Call test01

note:

SqlSession

• Instances of SqlSession are not thread-safe, so they cannot be shared.

• SqlSession needs to be properly closed after each use is completed, this closing operation is necessary

• SqlSession can directly call the method id to perform database operations, but we generally recommend using SqlSession to obtain the proxy class of the Dao interface and execute the proxy object method, which can perform type checking operations more safely

 

Guess you like

Origin blog.csdn.net/qq_45796208/article/details/110506295