MyBatis-04-notes

MyBatis interface proxy mode realizes Dao layer

Realize Dao in interface proxy mode

1 Introduction to agent development methods

Using Mybatis's agent development method to achieve the development of the DAO layer, this method is the mainstream for us to enter the enterprise later.

To implement the Dao layer in the traditional way, we have to write both the interface and the implementation class. The MyBatis framework can help us omit the implementation class steps of writing the Dao layer interface. The programmer only needs to write the Mapper interface (equivalent to the Dao interface), and the Mybatis framework creates the dynamic proxy object of the interface according to the interface definition. The method body of the proxy object is consistent with the Dao interface implementation class method in the Dao layer in the traditional way of MyBatis .

Mapper interface development needs to follow the following specifications:

1) The namespace in the Mapper.xml file is the same as the fully qualified name of the mapper interface

2) The Mapper interface method name is the same as the id of each statement defined in Mapper.xml

3) The input parameter type of the Mapper interface method is the same as the parameterType of each SQL defined in mapper.xml

4) The output parameter type of the Mapper interface method is the same as the resultType of each SQL defined in mapper.xml

to sum up:

The method of interface development: programmers only need to define the interface to operate the database, so how to create specific objects?

1. The programmer is responsible for defining the interface

2. In operating the database, the mybatis framework generates proxy objects through dynamic proxy according to the interface, and is responsible for the crud operation of the database

2 Write the StudentMapper interface

Insert picture description here

3 Test agency case

Mapping configuration file modification

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--
    mapper:核心根标签
    namespace属性:名称空间
-->
<!--<mapper namespace="StudentMapper">  1) Mapper.xml文件中的namespace与mapper接口的全限定名相同**-->
<mapper namespace="com.itheima.mapper.StudentMapper">
    <!--
        select:查询功能的标签
        id属性:唯一标识
        resultType属性:指定结果映射对象类型
        parameterType属性:指定参数映射对象类型
    -->
    <select id="selectAll" resultType="student">
        SELECT * FROM student
    </select>
    <select id="selectById" resultType="student" parameterType="int">
        SELECT * FROM student WHERE id = #{id}
    </select>
</mapper> 

The core configuration file remains unchanged

The database parameter configuration file remains unchanged

Delete the dao layer implementation class StudentMapperImpl

Modify the service implementation class StudentServiceImpl (because there is no dao layer implementation class, and now use the dynamic proxy object of the interface created by the Mybatis framework according to the interface StudentMappe definition)

package com.itheima.service.impl;
/*
    业务层实现类
 */
public class StudentServiceImpl implements StudentService {

    @Override
    public List<Student> selectAll() {
        List<Student> list = null;
        SqlSession sqlSession = null;
        InputStream is = null;
        try{
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");

            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);

            //4.获取StudentMapper接口的实现类对象  MyBatis根据接口StudentMappe定义创建的接口的动态代理对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();

            //5.通过实现类对象调用方法,接收结果
            list = mapper.selectAll();

        } catch (Exception e) {

        } finally {
            //6.释放资源
            if(sqlSession != null) {
                sqlSession.close();
            }
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //7.返回结果
        return list;
    }
}

Note that the above code is the implementation class method of the service layer. It looks similar to the previous implementation of the Dao layer in the traditional way of MyBatis . The main difference is that the StudentMapper mapper = sqlSession.getMapper(StudentMapper.class) gets the dynamic proxy object. Invoke the method.

4 Source code analysis

Analyze how the dynamic proxy object is generated?

Through the dynamic proxy development model, we only write an interface and do not write the implementation class. We finally obtain the org.apache.ibatis.binding.MapperProxy proxy object through the getMapper() method, and then execute the function.
And this proxy object is the dynamic proxy technology of JDK used by MyBatis to help us generate proxy implementation class objects. So that relevant persistence operations can be performed.

How is the analysis method performed?

The dynamic proxy implementation class object finally calls the mapperMethod.execute() method when executing the method. In this method, the switch statement is used to determine whether to add, modify, delete, and query operations according to the type of operation. The last step is back to the most native MyBatis SqlSession method to perform additions, deletions, and changes.

5 Knowledge summary

  • The interface proxy mode allows us to write only the interface, and the implementation class object is generated by MyBatis.
  • Implementation rules:
  • 1. The name space in the mapping configuration file must be the same as the full class name of the Dao layer interface.
  • 2. The id attribute of the addition, deletion, modification, and check tag in the mapping configuration file must be the same as the method name of the Dao layer interface.
  • 3. The parameterType attribute of the addition, deletion, modification, and check tag in the mapping configuration file must be the same as the parameter of the Dao layer interface method.
  • 4. The resultType attribute of the addition, deletion, modification, and check tag in the mapping configuration file must be the same as the return value of the Dao layer interface method.
  • Get dynamic proxy object
  • Get the getMapper() method in the SqlSession function class of the dynamic proxy object.