mybatis@Intercepts的⽤法解读
⽬录
mybatis @Intercepts的⽤法
1.类
2.配置
3.测试接⼝及配置
4.测试
5.结果
mybatis @Intercepts⼩例⼦
1.⼯作⽬录
2.数据库mysql
3.
4.配置⽂件
5.配置⽂件
6.测试⽂件
7.⼯具类
mybatis @Intercepts的⽤法
1.类
stmybatis.interceptor;
import java.util.Properties;
import org.utor.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 Logger(getClass());
public Object intercept(Invocation invocation) throws Throwable {
// TODO Auto-generated method stub
log.info("");
// 获取原始sql语句
MappedStatement mappedStatement = (MappedStatement) Args()[0];
Object parameter = Args()[1];
log4j2 logger标签BoundSql boundSql = BoundSql(parameter);
String oldsql = Sql();
log.info("old:"+oldsql);
// 改变sql语句
BoundSql newBoundSql = new Configuration(), oldsql + " where id=1",
MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
// 继续执⾏
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.Configuration(), ms.getId(), newSqlSource,
builder.FetchSize());
builder.StatementType());
builder.KeyGenerator());
if (ms.getKeyProperties() != null) {
for (String keyProperty : ms.getKeyProperties()) {
builder.keyProperty(keyProperty);
}
builder.Timeout());
builder.ParameterMap());
builder.Cache());
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 "-////DTD Config 3.0//EN"
"/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="stmybatis.interceptor.SqlInterceptor" />
</plugins>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="sql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true" />    <property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/testmybatis/l" />
</mappers>
</configuration>
3.测试接⼝及配置
del;
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;
}
}
stmybatis.dao;
import java.util.List;
import org.apache.ibatis.annotations.Select;
del.Test;
public interface TestMapper {
public List<Test> test();
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd">
<mapper namespace="stmybatis.dao.TestMapper">
<select id="test" resultType="del.Test">
select * from test
</select>
</mapper>
4.测试
try {
String resource = "com/l";
InputStream inputStream = ResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
TestMapper Mapper(TestMapper.class);
List<Test> st();
sessionmit();
log.JSONString(tests));
} finally {
session.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
5.结果
配置了的情况下
2018-08-07 14:14:18 DEBUG [stmybatis.st] ==> Preparing: select * from test where id=1
2018-08-07 14:14:18 DEBUG [stmybatis.st] ==> Parameters:
2018-08-07 14:14:18 DEBUG [stmybatis.st] <== Total: 1
2018-08-07 14:14:18 INFO [stlanjie] [{"id":1,"name":"adb"}]
没配置的情况下
2018-08-07 14:15:48 DEBUG [stmybatis.st] ==> Preparing: select * from test
2018-08-07 14:15:48 DEBUG [stmybatis.st] ==> Parameters:
2018-08-07 14:15:48 DEBUG [stmybatis.st] <== Total: 8
2018-08-07 14:15:48 INFO [stlanjie] [{"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、l省略。使⽤mybatis⾃动代码⽣成⼯具⽣成:mybatis-generator-core-1.3.2。(此处略)3.
MyInterceptor.java
package batis.interceptor;
import java.sql.Connection;
import java.util.Properties;
import org.utor.Executor;
import org.utor.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 = Property("prop1");
String prop2 = Property("prop2");
System.out.println(prop1 + "------" + prop2);
}
}
4.配置⽂件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-////DTD Config 3.0//EN"
"/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="del"/>
</typeAliases>
<plugins>
<plugin interceptor="batis.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/l"/>
</mappers>
</configuration>
5.配置⽂件
jdbc.properties
sql.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 batis.service;
import org.apache.ibatis.session.SqlSession;
import com.tiantian.base.MyBatisUtil;
import batis.domain.User;
public class TestMyBatis {
public static void main(String[] args) {
SqlSession session = SqlSession();
/**
* 映射sql的标识字符串,
* batis.mapper.userMapper是l⽂件中mapper标签的namespace属性的值,        * selectByPrimaryKey是select标签的id属性值,通过select标签的id属性值就可以到要执⾏的SQL
*/
String statement = "batis.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 {

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。