MyBatis 自定义插件

2020-10-14

1、Maven 依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>constxiong</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>mybatis-plugin</artifactId>

    <dependencies>
        <!-- MySQL 8.0.21 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <!-- MyBatis -->
        <dependency>
		  <groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.5.5</version>
		</dependency>

    </dependencies>

    <build>

    </build>
</project>

 

2、MyBatis 配置,加入 plugin 配置

<?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>
    <plugins>
        <plugin interceptor="constxiong.plugin.ExamplePlugin">
        </plugin>
    </plugins>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://172.31.32.184:3306/constxiong?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="constxiong@123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="constxiong/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

 

3、Mapper 接口

package constxiong.mapper;

import constxiong.po.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * UserMapper 接口,映射对数据库的操作
 */
public interface UserMapper {

    List<User> selectUsers();

    int insertUser(User user);

    int deleteUsers();

}

 

4、Mapper xml

<?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="constxiong.mapper.UserMapper">

    <select id="selectUsers" resultType="constxiong.po.User">
        select * from user
    </select>

    <insert id="insertUser" parameterType="constxiong.po.User">
        insert into user values(#{id}, #{name})
    </insert>

    <delete id="deleteUsers">
      delete from user
    </delete>

</mapper>

 

5、PO

package constxiong.po;

/**
 * 用户表模型
 */
public class User {
    private Integer id;

    private String name;

    private String mc;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMc() {
        return mc;
    }

    public void setMc(String mc) {
        this.mc = mc;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", mc='" + mc + '\'' +
                '}';
    }
}

 

6、插件实现类

package constxiong.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Arrays;
import java.util.List;

/**
 * MyBatis 插件
 */
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class ExamplePlugin implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        for (Object arg : invocation.getArgs()) {
            System.out.println("参数:" + arg);
        }
        System.out.println("方法:" + invocation.getMethod());
        System.out.println("目标对象:" + invocation.getTarget());
        Object result = invocation.proceed();

        //只获取第一个数据
        if (result instanceof List){
            System.out.println("原集合数据:" + result);
            System.out.println("只获取第一个对象");
            List list = (List)result;
            return Arrays.asList(list.get(0));
        }
        return result;
    }
}

 

7、测试类

ConstXiong 备案号:苏ICP备16009629号-3