就可以做分页或者其他功能,就不需要在映射文件写了。
通过
http://blog.csdn.net/hfmbook/article/details/41985853
这个大佬写的来学习的,写的很详细的
以下是代码
TestPlugin.java
package com.hgf.ssm.util; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import java.lang.reflect.Field; import java.sql.Connection; import java.util.Properties; /** * Created by hasee on 2017/1/22. * 测试MyBatis插件,功能其实感觉就是过滤器 */ @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) public class TestPlugin implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { System.out.println("intercept"); //获取RoutingStatementHandler对象 RoutingStatementHandler statementHandler = (RoutingStatementHandler)invocation.getTarget(); //通过反射得到delegate的filed类 Field field = statementHandler.getClass().getDeclaredField("delegate"); Object value = null; //判断field是否需要进行java语言访问检查,参考 https://my.oschina.net/nixi0608/blog/724343 if (field.isAccessible()) { value = field.get(statementHandler); } else { field.setAccessible(true); value = field.get(statementHandler); field.setAccessible(false); } StatementHandler delegate = (StatementHandler)value; BoundSql boundSql = delegate.getBoundSql(); //获取当前sql语句 String sql = boundSql.getSql(); System.out.println(sql); return invocation.proceed(); } @Override public Object plugin(Object o) { System.out.println("plugin"); if (o instanceof StatementHandler) { return Plugin.wrap(o, this); } else { return o; } } @Override public void setProperties(Properties properties) { } }
spring-mybatis.xml
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" > <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath*:com/hgf/ssm/dao/mapper/*.xml"></property> <property name="typeAliasesPackage" value="com.hgf.ssm.dao.po" /> <property name="configLocation" value="classpath:mybatis-configuration.xml" /> </bean>
mybatis-configuration.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <!-- MyBatis数据持久层配置文件 --> <configuration> <!-- 插件 --> <plugins> <!-- StatementHandler插件 --> <plugin interceptor="com.hgf.ssm.util.TestPlugin"> <property name="sqlid" value=".*Page" /> </plugin> </plugins> </configuration>