Mybatis插件使用

Mybatis插件

3W1H?

  1. why:为什么使用mybatis插件?

    1. sql语句提交至database(数据库),无控制。作为一款框架一般都有自己的拦截器,对框架内的内容进行控制。
    2. 可以拦截提交至database(数据库)的sql语句。
  2. who:谁要使用mybatis插件?

    1. mybatis要使用。
  3. what:什么地方使用mybatis插件?

    1. 在提交sql语句之时使用。
    2. mybatis配置文件中。
  4. how:如何使用mybatis插件?

    1. 配置xml文件

    2. 写对应的拦截器。

使用过程

配置xml文件

<configuration>
<!-- mybatis的插件 -->
    <plugins>
    	<!-- 插件类的位置 -->
        <plugin interceptor="com.hp.interceptor.MybatisInterceptor"></plugin>
    </plugins>
<!-- 告诉 MyBatis到哪里去找映射文件 -->
 <mappers>
    <mapper resource="com/hp/dao/mapper/ShopMapper.xml"/>
    <mapper resource="com/hp/dao/mapper/LoginMapper.xml"/>
    </mappers>
</configuration>

写plugin插件配置的对应类

实现Interceptor接口,这个Interceptor需要引入mybatis对应的包

import org.apache.ibatis.plugin.Interceptor;

Interceptor接口有三个方法:

public Object intercept(Invocation invocation) ;

​ 这个方法是拦截使用的,invocation可以获取mybatis中的sql语句。

​ 判断是否通过拦截器:return invocation.proceed();

​ 这里几乎可以获取所有向数据库提交的内容。

public Object plugin(Object arg0) ;

​ 通过这个插件。

​ 执行4次。循环判断要拦截哪一个类。

public void setProperties(Properties properties);

​ 获取mybatis的xml中配置plugin插件配置的数据。

	<plugins>
		<plugin interceptor="com.hp.interceptor.MybatisInterceptor">
			<property name="dbname" value="mysql"/>
 			<property name="version" value="5.6"/>
		</plugin>
	</plugins>
posted @ 2020-11-22 10:30  日落海平面  阅读(398)  评论(0)    收藏  举报