Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of MyBatis plug-in

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is the principle of MyBatis plug-in". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the principle of MyBatis plug-in"?

How to integrate paging plug-ins

Spring-Boot+Mybatis+PageHelper .

Introduce pom dependency

Com.github.pagehelper pagehelper-spring-boot-starter 1.2.3

Configure paging plug-in configuration items

Pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql

In service interface code

PageInfo selectUsersByName (int pageIndex, int pageSize)

In the service implementation class code

@ Override public PageInfo selectUsersByName (int pageIndex, int pageSize) {PageHelper.startPage (pageIndex, pageSize); List users = userMapper.selectUsersByName (null); return new PageInfo (users);}

Mapper code code

Select * from m_user `name` = # {userName} List selectUsersByName (@ Param ("userName") String userName)

Code in controller

@ GetMapping ("/ user/name") public PageInfo selectUsersByName (int pageIndex, int pageSize) {return userService.selectUsersByName (pageIndex, pageSize);}

And then we visit.

Http://localhost:9002/user/name?pageIndex=1&pageSize=10

Output result:

Output important item description:

PageNum: current page number.

PageSize: number of pages.

List: this is the business data we returned.

Total: total data.

HasNextPage: whether there is a next page.

Let's take a look at the output SQL:

It was found that two SQL:count and limit lines were actually executed.

Guess the implementation of the paging plug-in

1. This paging plug-in is nothing more than splicing a limit and making a count query on our query conditions.

two。 We are using Mysql as the database here, but if it is Oracle, it is not limit, so there is a solution for multiple databases.

3. Intercept and do sql and related processing before there is no plug-in.

According to the Quick start plugin on the official website

Here is a passage from the official website:

MyBatis allows you to intercept calls at some point during the execution of the mapping statement. By default, the method calls that MyBatis allows you to intercept with plug-ins include:

Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)

ParameterHandler (getParameterObject, setParameters)

ResultSetHandler (handleResultSets, handleOutputParameters)

StatementHandler (prepare, parameterize, batch, update, query)

The details of the methods in these classes can be found by looking at the signature of each method, or by looking directly at the source code in the MyBatis distribution. If you want to do more than just monitor method calls, you'd better have a good understanding of the behavior of the method to be overridden. Because when you try to modify or override the behavior of an existing method, you are likely to break the core module of MyBatis. These are lower-level classes and methods, so be especially careful when using plug-ins.

With the powerful mechanism provided by MyBatis, using a plug-in is as simple as implementing the Interceptor interface and specifying the method signature you want to intercept.

Then let's try to write a plug-in according to the official.

Custom plug-in

@ Intercepts ({@ Signature (type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class TianPlugin implements Interceptor {private Properties properties = new Properties (); @ Override public Object intercept (Invocation invocation) throws Throwable {System.out.println ("a Mybatis plug-in written by Lao Tian-start"); Object returnObject = invocation.proceed () System.out.println ("a Mybatis plugin written by Lao Tian-end"); return returnObject;}}

Then inject the plug-in class into the container.

The customization here is entirely a case given on the official website. Seeing a update in the custom plug-in class, we speculate that it must be necessary to execute update to be intercepted.

Access the previous code: http://localhost:9002/updateUser

Succeed.

This is sure that you will think that when we first started to learn dynamic proxies, didn't we just do something before and after the method to be called?

That's exactly what the plug-in for Mybatis does.

Let's analyze the official words and our custom plug-ins.

Analysis.

First of all, our custom plug-in must be for the following four classes and methods.

Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)

ParameterHandler (getParameterObject, setParameters)

ResultSetHandler (handleResultSets, handleOutputParameters)

StatementHandler (prepare, parameterize, batch, update, query)

Second, we must implement the Interceptor of Mybatis.

The role of three methods in Interceptor:

Intercept (): the place where intercepting content is performed, such as doing some own processing before and after calling some kind of method, simply printing the log.

Plugin (): determines whether the intercept () method is triggered.

SetProperties (): pass the property parameters we configured to the custom interceptor (this can be ignored for the time being, we'll write a relatively complete plug-in later, and you'll see what it does).

Plugin method

Default Object plugin (Object target) {return Plugin.wrap (target, this);}

The default implementation method, which calls the Plugin.wrap () method.

Public class Plugin implements InvocationHandler {private Object target; private Interceptor interceptor; private Map, Set > signatureMap = getSignatureMap (interceptor); Class type = target.getClass (); Class [] interfaces = getAllInterfaces (type, signatureMap); if (interfaces.length > 0) {/ / create JDK dynamic proxy object return Proxy.newProxyInstance (type.getClassLoader (), interfaces, new Plugin (target, interceptor, signatureMap)) } return target;} @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {try {Set methods = signatureMap.get (method.getDeclaringClass ()) / / determine whether the method needs to be intercepted (very important) if (methods! = null & & methods.contains (method)) {/ / callback intercept () method return interceptor.intercept (new Invocation (target, method, args);} return method.invoke (target, args);} catch (Exception e) {throw ExceptionUtil.unwrapThrowable (e);}} / /. Omit other irrelevant codes}

Isn't this just a JDK dynamic agent?

Map

So, let's not always say that the reflection performance is poor, that's because you don't cache the reflection results of an object like Mybatis.

This comment is important to determine whether it is a method that needs to be intercepted. Once you ignore it, you don't know how Mybatis determines whether or not to intercept content. Keep in mind.

What does Plugin.wrap (target, this) do?

Using JDK's dynamic proxy, create a delegate proxy object for the target object to implement method interception and enhancement, which calls back the intercept () method.

Why write notes? What do annotations mean?

There are a bunch of comments on our custom plug-ins, don't be afraid.

Mybatis states that plug-ins must write Annotation annotations, which are necessary, not optional.

Intercepts ({@ Signature (type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class TianPlugin implements Interceptor {

@ Intercepts note: load a @ Signature list, and a @ Signature is actually a method encapsulation that needs to be intercepted. So, if an interceptor wants to intercept multiple methods, it is naturally a @ Signature list.

Type= Executor.class, method = "update", args = {MappedStatement.class,Object.class}

Explanation: to intercept the query () method in the Executor interface, the parameter type is args list.

What if you want to intercept multiple methods?

@ Documented @ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.TYPE) public @ interface Intercepts {Signature [] value ();}

This is easy. We can store multiple @ Intercepts annotations in the @ Signature annotation.

For example, the previous paging plug-in intercepts multiple methods.

Why intercept both query methods? Because there are two query methods in Executor.

At this point, I believe that you have a deeper understanding of "what is the principle of the MyBatis plug-in", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report