mybatis @Intercepts的用法解读

目录
  • mybatis @Intercepts的用法
    • 1.拦截器类
    • 2.拦截器配置
    • 3.测试接口及配置
    • 4.测试
    • 5.结果
  • mybatis @Intercepts小例子
    • 1.工作目录
    • 2.数据库mysql
    • 3.拦截器
    • 4.配置文件
    • 5.配置文件
    • 6.测试文件
    • 7.工具类

mybatis @Intercepts的用法

1.拦截器类

package com.testmybatis.interceptor;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

@Intercepts({ @org.apache.ibatis.plugin.Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class SqlInterceptor implements Interceptor {

	private Logger log=Logger.getLogger(getClass());
	public Object intercept(Invocation invocation) throws Throwable {
		// TODO Auto-generated method stub

		log.info("Interceptor......");

		// 获取原始sql语句
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		Object parameter = invocation.getArgs()[1];
		BoundSql boundSql = mappedStatement.getBoundSql(parameter);
		String oldsql = boundSql.getSql();
		log.info("old:"+oldsql);

		// 改变sql语句
		BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), oldsql + " where id=1",
				boundSql.getParameterMappings(), boundSql.getParameterObject());
		MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
		invocation.getArgs()[0] = newMs;

		// 继续执行
		Object result = invocation.proceed();
		return result;
	}

	public Object plugin(Object target) {
		// TODO Auto-generated method stub
		return Plugin.wrap(target, this);
	}

	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
	}

	// 复制原始MappedStatement
	private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
		MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
				ms.getSqlCommandType());
		builder.resource(ms.getResource());
		builder.fetchSize(ms.getFetchSize());
		builder.statementType(ms.getStatementType());
		builder.keyGenerator(ms.getKeyGenerator());
		if (ms.getKeyProperties() != null) {
			for (String keyProperty : ms.getKeyProperties()) {
				builder.keyProperty(keyProperty);
			}
		}
		builder.timeout(ms.getTimeout());
		builder.parameterMap(ms.getParameterMap());
		builder.resultMaps(ms.getResultMaps());
		builder.cache(ms.getCache());
		builder.useCache(ms.isUseCache());
		return builder.build();
	}

	public static class BoundSqlSqlSource implements SqlSource {
		BoundSql boundSql;
		public BoundSqlSqlSource(BoundSql boundSql) {
			this.boundSql = boundSql;
		}

		public BoundSql getBoundSql(Object parameterObject) {
			return boundSql;
		}
	}
}

2.拦截器配置

<?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="com.testmybatis.interceptor.SqlInterceptor" />
	</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://127.0.0.1:3306/test?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<mapper resource="com/testmybatis/dao/TestMapper.xml" />
	</mappers>
</configuration>

3.测试接口及配置

package com.testmybatis.model;
import java.io.Serializable;
public class Test implements Serializable{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String toString(){
		return "id:"+id+" name:"+name;
	}
}
package com.testmybatis.dao;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.testmybatis.model.Test;
public interface TestMapper {
	public List<Test> test();
}
<?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="com.testmybatis.dao.TestMapper">

	<select id="test" resultType="com.testmybatis.model.Test">
		select * from test
	</select>

</mapper>

4.测试

	try {
			String resource = "com/testmybatis/mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			SqlSession session = sqlSessionFactory.openSession();
			try {
				TestMapper mapper=session.getMapper(TestMapper.class);
				List<Test> tests=mapper.test();
				session.commit();
				log.info(JSON.toJSONString(tests));

			} finally {
				session.close();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

5.结果

配置了拦截器的情况下

2018-08-07 14:14:18 DEBUG [com.testmybatis.dao.TestMapper.test] ==> Preparing: select * from test where id=1

2018-08-07 14:14:18 DEBUG [com.testmybatis.dao.TestMapper.test] ==> Parameters:

2018-08-07 14:14:18 DEBUG [com.testmybatis.dao.TestMapper.test] <== Total: 1

2018-08-07 14:14:18 INFO [com.testmybatis.testlanjie] [{"id":1,"name":"adb"}]

没配置拦截器的情况下

2018-08-07 14:15:48 DEBUG [com.testmybatis.dao.TestMapper.test] ==> Preparing: select * from test

2018-08-07 14:15:48 DEBUG [com.testmybatis.dao.TestMapper.test] ==> Parameters:

2018-08-07 14:15:48 DEBUG [com.testmybatis.dao.TestMapper.test] <== Total: 8

2018-08-07 14:15:48 INFO [com.testmybatis.testlanjie] [{"id":1,"name":"adb"},{"id":2,"name":"dafdsa"},{"id":3,"name":"dafa"},{"id":4,"name":"fffff"},{"id":16,"name":"test"},{"id":17,"name":"test"},{"id":18,"name":"test"},{"id":19,"name":"zhenshide"}]

mybatis @Intercepts小例子

这只是一个纯碎的mybatis的只针对@Intercepts应用的小列子,没有和spring做集成。

1.工作目录

2.数据库mysql

建立一个数据库表、实体对象User、UserMapper.java、UserMapper.xml省略。

使用mybatis自动代码生成工具生成:mybatis-generator-core-1.3.2。(此处略)

3.拦截器

MyInterceptor.java

package com.tiantian.mybatis.interceptor;
import java.sql.Connection;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
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.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
@Intercepts( {
    @Signature(method = "query", type = Executor.class, args = {
           MappedStatement.class, Object.class, RowBounds.class,
           ResultHandler.class }),
    @Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class }) })
public class MyInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        System.out.println("Invocation.proceed()");
        return result;
    }
    @Override
    public Object plugin(Object target) {
        // TODO Auto-generated method stub
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
        String prop1 = properties.getProperty("prop1");
        String prop2 = properties.getProperty("prop2");
        System.out.println(prop1 + "------" + prop2);
    }
}

4.配置文件

mybatis-config.xml

<?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>
    <properties resource="jdbc.properties"></properties>
    <typeAliases>
       <package name="com.tiantian.mybatis.model"/>
    </typeAliases>
    <plugins>
       <plugin interceptor="com.tiantian.mybatis.interceptor.MyInterceptor">
           <property name="prop1" value="prop1"/>
           <property name="prop2" value="prop2"/>
       </plugin>
    </plugins>
    <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC" />
           <dataSource type="POOLED">
              <property name="driver" value="${driver}" />
              <property name="url" value="${url}" />
              <property name="username" value="${username}" />
              <property name="password" value="${password}" />
           </dataSource>
       </environment>
    </environments>
    <mappers>
       <mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

5.配置文件

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/database_yxl
username=root
password=123456
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

6.测试文件

TestMyBatis.java

package com.tiantian.mybatis.service;
import org.apache.ibatis.session.SqlSession;
import com.tiantian.base.MyBatisUtil;
import com.tiantian.mybatis.domain.User;
public class TestMyBatis {
    public static void main(String[] args) {
        SqlSession session = MyBatisUtil.getSqlSession();
        /**
         * 映射sql的标识字符串,
         * com.tiantian.mybatis.mapper.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
         * selectByPrimaryKey是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "com.tiantian.mybatis.mapper.UserMapper.selectByPrimaryKey";//映射sql的标识字符串
        //执行查询返回一个唯一user对象的sql
        User user = session.selectOne(statement, 1);
        System.out.println(user);
    }
}

输出结果:

prop1------prop2

Invocation.proceed()

Invocation.proceed()

[id:1;username:测试;password:sfasgfaf]

7.工具类

MyBatisUtil.java

package com.tiantian.base;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
    public static SqlSessionFactory getSqlSessionFactory() {
        String resource = "mybatis-config.xml";
        // 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
        // 构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        return sessionFactory;
    }
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot整合MybatisSQL过滤@Intercepts的实现

    场景: 系统模块查询数据库需要根据用户的id去筛选数据.那么如果在 每个sql加user_id的过滤显然不明确.所以要在查询前将sql拼接上条件,做统一管理. 开发环境: spring boot + mybatis 只需一个拦截类即可搞定(在看代码前需要了解注解@Intercepts()): @Component @Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStateme

  • Mybatis Interceptor 拦截器的实现

    Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最好了解下它的原理,以便写出安全高效的插件. 拦截器(Interceptor)在 Mybatis 中被当做插件(plugin)对待,官方文档提供了 Executor,ParameterHandler,ResultSetHandler,StatementHandler 共4种,并且提示"这些类中方法的细

  • mybatis 自定义实现拦截器插件Interceptor示例

    首先熟悉一下Mybatis的执行过程,如下图: 类型 先说明Mybatis中可以被拦截的类型具体有以下四种: 1.Executor:拦截执行器的方法. 2.ParameterHandler:拦截参数的处理. 3.ResultHandler:拦截结果集的处理. 4.StatementHandler:拦截Sql语法构建的处理. 规则 Intercepts注解需要一个Signature(拦截点)参数数组.通过Signature来指定拦截哪个对象里面的哪个方法.@Intercepts注解定义如下: @D

  • mybatis @Intercepts的用法解读

    目录 mybatis @Intercepts的用法 1.拦截器类 2.拦截器配置 3.测试接口及配置 4.测试 5.结果 mybatis @Intercepts小例子 1.工作目录 2.数据库mysql 3.拦截器 4.配置文件 5.配置文件 6.测试文件 7.工具类 mybatis @Intercepts的用法 1.拦截器类 package com.testmybatis.interceptor; import java.util.Properties; import org.apache.i

  • spring的@Transactional注解用法解读

    概述 事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性. Spring Framework对事务管理提供了一致的抽象,其特点如下: 为不同的事务API提供一致的编程模型,比如JTA(Java Transaction API), JDBC, Hibernate, JPA(Java Persistence API和JDO(Java Data Objects) 支持声明式事务管理,特别是基于注解的声明式事务管理,简单易用 提供比其他事务API如JTA更简单的编程式事务管

  • Mybatis Trim标签用法简单介绍

    废话不多说了,直接给大家贴代码了,具体代码如下所示: <update id="updateAuditStateAndType" parameterType="Java.util.Map"> update social_building_info <trim prefix="set" prefixOverrides=","> <if test="auditState != null and

  • Mybatis choose when用法实例代码

    mybatis choose when的用法实现代码如下所示: mapper.xml: <select id="query" resultType="map" parameterType="map"> select <choose> <when test="cityId == '00' "> a.city_id as CITYID, </when> <otherwise&g

  • Mybatis useGeneratedKeys参数用法及问题小结

    目录 什么是useGeneratedKeys? 如何使用? 一.配置全局的配置文件 二.在xml映射器中配置useGeneratedKeys参数 三.在接口映射器中设置useGeneratedKeys参数 遇到的问题 什么是useGeneratedKeys? 官方的说法是该参数的作用是:“允许JDBC支持自动生成主键,需要驱动兼容”,如何理解这句话的意思? 其本意是说:对于支持自动生成记录主键的数据库,如:MySQL,SQL Server,此时设置useGeneratedKeys参数值为true

  • vuex中getters的基本用法解读

    目录 getters的基本用法解读 一.getter 定义 二.使用方法 三.mapGetters辅助函数 四.getters注意事项 getters的两种调用方法 方法一 方法二 getters的基本用法解读 一.getter 定义 Vuex允许我们在store中定义"getter" ,用于对state中存储的数据进行过滤操作. 就像vue生命周期中的computed一样,getter的返回值 会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算 二.使用方法 1.通

  • Mybatis @SelectKey用法解读

    目录 Mybatis @SelectKey用法 用处 用法 属性 注意 Mybatis selectKey 采坑笔记 1.现象描述 2.问题排查 3. selectKey 用法再认识 4.selectKey用法的坑 Mybatis @SelectKey用法 用处 主要用来解决主键自增问题 用法 @SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="clusterId", before=false,

  • Spring中SmartLifecycle的用法解读

    目录 Spring SmartLifecycle用法 SmartLifecycle 是一个接口 SmartLifecycle 解读 1.接口定义 2.应用 Spring SmartLifecycle用法 Spring SmartLifecycle 在容器所有bean加载和初始化完毕执行 在使用Spring开发时,我们都知道,所有bean都交给Spring容器来统一管理,其中包括每一个bean的加载和初始化. 有时候我们需要在Spring加载和初始化所有bean后,接着执行一些任务或者启动需要的异

  • mybatis之foreach用法详解

    在做mybatis的mapper.xml文件的时候,我们时常用到这样的情况:动态生成sql语句的查询条件,这个时候我们就可以用mybatis的foreach了 foreach元素的属性主要有item,index,collection,open,separator,close. item:集合中元素迭代时的别名,该参数为必选. index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选 open:foreach代码的开始符号,一般是(和close=")

  • R语言-summary()函数的用法解读

    summary():获取描述性统计量,可以提供最小值.最大值.四分位数和数值型变量的均值,以及因子向量和逻辑型向量的频数统计等. 结果解读如下: 1. 调用:Call lm(formula = DstValue ~ Month + RecentVal1 + RecentVal4 + RecentVal6 + RecentVal8 + RecentVal12, data = trainData) 当创建模型时,以上代码表明lm是如何被调用的. 2. 残差统计量:Residuals Min 1Q M

随机推荐