Handwritten MyBatis, Creating an Open Source Framework by Hand (Part 4: Winning a Triumph) - Article 272

Keywords: Mybatis Spring Java SpringBoot

Links to the original text: https://mp.weixin.qq.com/s?__biz=MzA4ODIyMzEwMg==&mid=2447534090&idx=1&sn=3ca3117710bfccb10e7ba9b5cee86ab9&chksm=843bb41bb34c3d0dbe0eefea2877882bef2e43df76335f0a1fe7f46d8bfacdc99034498ab5f8&token=1895825389&lang=zh_CN#rd


Explain

MyBatis version: 3.5.1

Relevant historical articles (before reading this article, you may need to look at the previous series (vii) br/>.

 

Relevant historical articles (before reading this article, you may need to look at the previous series first)

Spring Boot MyBatis: You deserve it
Can MyBatis Get Out of SpringA Picture Overview of MyBatis's Working PrinciplesFrom the source code, MyBatis is so simpleWhat's MyBatis's Mapper?`

Handwritten MyBatis, Creating an Open Source Framework Purely by Hand (Part 1: Return of the Wind and Cloud)

Handwritten MyBatis, Creating Open Source Framework Purely by Hand (Part 2: King Over the World)

Handwritten MyBatis, Creating an Open Source Framework Purely by Hand (Part 3: Operational Strategies)

 

Preface

In the stratagem, thousands of miles away from winning, it's time to finish. Take your guys out and put a bayonet on them.
The last article has been able to use SqlSession to query and return results. In this article, we are joining the Swiss Army Knife Mapper.

I. Analysis

In SqlSession, a getMapper method is provided. In DefaultSqlSession, a MapperProxy agent is instantiated using Proxy, and the MapperProxy agent gets SqlSession, where it performs Sql operations and then results.

 

II. Coding

2.1 MapperProxy

MapperProxy is the core of mapper's final execution:

package com.kfit.mybatis.session.impl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

import com.kfit.mybatis.session.SqlSession;

public class MapperProxy implements InvocationHandler{
	private SqlSession sqlSession;
	public MapperProxy(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String statement = method.getDeclaringClass().getName()+"."+method.getName();
		//The isAssignableFrom method is to determine whether it is the parent of a class or not.
		if(Collection.class.isAssignableFrom(method.getReturnType())) {
			//If the return value is a collection, then call selectList
			return sqlSession.selectList(statement,null==args?null:args[0]);
		}else {
			return sqlSession.selectOne(statement,null==args?null:args[0]);
		}
	}
	
}

 

Explain:

(1) Since MapperProxy is a proxy class, it is necessary to implement the Invoke method of the interface InvocationHandler.

(2) In Invoke method, SqlSession is directly used to execute, so the main core is to determine what method to execute. Now we can judge whether to execute selectOne or SelectList by whether the return value is a collection.

2.2 SqlSession

Add the getMapper method in SqlSession:

public interface SqlSession {
	 <T> T selectOne(String statement, Object parameter);
	 <E> List<E> selectList(String statement);
	 <E> List<E> selectList(String statement, Object parameter);
	 <T> T getMapper(Class<T> type);
}

 

The getMapper method is implemented in DefaultSqlSession:

	@SuppressWarnings("unchecked")
	public <T> T getMapper(Class<T> type) {
		T newProxyInstance = (T) Proxy.newProxyInstance(type.getClassLoader(),new Class[]{type},new MapperProxy(this));
		return newProxyInstance;
	}

2.3 Test

Well, write a code test.

public static void main(String[] args) {
		String resource = "mybatis-config.xml";
		InputStream inputStream = App.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		System.out.println(sqlSessionFactory);
		System.out.println(sqlSessionFactory.getConfiguration().getJdbcProperties().getUrl());
		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		
		Demo demo = null;
		List<Demo> demos = null;
		
		
		//Use Mapper
		DemoMapper demoMapper = sqlSession.getMapper(DemoMapper.class);
		demo = demoMapper.getById(1);
		System.out.println(demo);
		demos = demoMapper.getAll();
		System.out.println(demos);
	}

Look at the results of the operation:

Demo [id=1, name = Zhang San1]
[Demo [id=1, name = Zhang San 1], Demo [id=9, name = Zhang San], Demo [id=10, name = Zhang San], Demo [id=11, name = Zhang San], Demo [id=12, name = Zhang San], Demo [id=13, name = Zhang San]]

It is obvious that the results of execution are the same as those of direct SqlSession calls.

Well, the article about handwritten MyBatis comes to an end first. By handwriting mybatis, you must have a higher level of understanding of MyBatis.

 

I am me, a firework of different colours.
I am just me, a special apple.

 


YA Wukong College: http://t.cn/Rg3fKJD 

There are Spring Boot related courses in the college! Click "Read the original text" to view!

SpringBoot Video: http://t.cn/R3QepWG 
Spring Cloud Video: http://t.cn/R3QeRZc 
SpringBoot Shiro Video: http://t.cn/R3QDMbh 
SpringBoot Communication platform: http://t.cn/R3QDhU0 
SpringData and JPA Video: http://t.cn/R1pSojf 
SpringSecurity5.0 Video: http://t.cn/EwlLjHh 
Sharding-JDBC Sub-database, sub-table and actual combat: http://t.cn/E4lpD6e

Posted by manmadareddy on Thu, 29 Aug 2019 02:33:58 -0700