最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

mybatis @Intercepts的用法解讀

 更新時(shí)間:2021年09月24日 08:47:58   作者:knife1220  
這篇文章主要介紹了mybatis @Intercepts的用法解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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語(yǔ)句
		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語(yǔ)句
		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;
 
		// 繼續(xù)執(zhí)行
		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 
	}
 
	// 復(fù)制原始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.測(cè)試接口及配置

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.測(cè)試

	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.結(jié)果

配置了攔截器的情況下

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小例子

這只是一個(gè)純碎的mybatis的只針對(duì)@Intercepts應(yīng)用的小列子,沒有和spring做集成。

1.工作目錄

2.數(shù)據(jù)庫(kù)mysql

建立一個(gè)數(shù)據(jù)庫(kù)表、實(shí)體對(duì)象User、UserMapper.java、UserMapper.xml省略。

使用mybatis自動(dòng)代碼生成工具生成: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
#定義初始連接數(shù)
initialSize=0
#定義最大連接數(shù)
maxActive=20
#定義最大空閑
maxIdle=20
#定義最小空閑
minIdle=1
#定義最長(zhǎng)等待時(shí)間
maxWait=60000

6.測(cè)試文件

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的標(biāo)識(shí)字符串,
         * com.tiantian.mybatis.mapper.userMapper是userMapper.xml文件中mapper標(biāo)簽的namespace屬性的值,
         * selectByPrimaryKey是select標(biāo)簽的id屬性值,通過select標(biāo)簽的id屬性值就可以找到要執(zhí)行的SQL
         */
        String statement = "com.tiantian.mybatis.mapper.UserMapper.selectByPrimaryKey";//映射sql的標(biāo)識(shí)字符串
        //執(zhí)行查詢返回一個(gè)唯一user對(duì)象的sql
        User user = session.selectOne(statement, 1);
        System.out.println(user);
    }
}

輸出結(jié)果:

prop1------prop2

Invocation.proceed()

Invocation.proceed()

[id:1;username:測(cè)試;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的配置文件(它也加載關(guān)聯(lián)的映射文件)
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
        // 構(gòu)建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);
    }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot @Cacheable自定義KeyGenerator方式

    SpringBoot @Cacheable自定義KeyGenerator方式

    這篇文章主要介紹了SpringBoot @Cacheable自定義KeyGenerator方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Spring Boot應(yīng)用事件監(jiān)聽示例詳解

    Spring Boot應(yīng)用事件監(jiān)聽示例詳解

    這篇文章主要給大家介紹了關(guān)于Spring Boot應(yīng)用事件監(jiān)聽的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • SpringBoot整合Mybatis Plus實(shí)現(xiàn)基本CRUD的示例代碼

    SpringBoot整合Mybatis Plus實(shí)現(xiàn)基本CRUD的示例代碼

    Mybatis Plus是在Mybatis的基礎(chǔ)上的增強(qiáng),使得我們對(duì)一些基本的CRUD使用起來更方便,本文主要介紹了SpringBoot整合Mybatis Plus實(shí)現(xiàn)基本CRUD的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-05-05
  • Java使用NioSocket手動(dòng)實(shí)現(xiàn)HTTP服務(wù)器

    Java使用NioSocket手動(dòng)實(shí)現(xiàn)HTTP服務(wù)器

    本篇文章主要介紹了Java使用NioSocket手動(dòng)實(shí)現(xiàn)HTTP服務(wù)器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-05-05
  • Java基礎(chǔ)之內(nèi)部類與代理知識(shí)總結(jié)

    Java基礎(chǔ)之內(nèi)部類與代理知識(shí)總結(jié)

    今天帶大家復(fù)習(xí)Java的基礎(chǔ)知識(shí),文中有非常詳細(xì)的介紹及圖文示例,對(duì)正在學(xué)習(xí)Java的小伙伴們很有幫助,需要的朋友可以參考下
    2021-06-06
  • SpringBoot+actuator和admin-UI實(shí)現(xiàn)監(jiān)控中心方式

    SpringBoot+actuator和admin-UI實(shí)現(xiàn)監(jiān)控中心方式

    這篇文章主要介紹了SpringBoot+actuator和admin-UI實(shí)現(xiàn)監(jiān)控中心方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • HashMap每次擴(kuò)容為什么是2倍

    HashMap每次擴(kuò)容為什么是2倍

    當(dāng)HashMap在初始化沒有指定容量的情況下,首次添加元素時(shí),數(shù)組的容量為16;當(dāng)超出閾值,數(shù)組容量為擴(kuò)容為之前的2倍,為什么HashMap每次擴(kuò)容都是之前的2倍?下面就介紹一下
    2024-11-11
  • Spring實(shí)現(xiàn)定時(shí)任務(wù)的兩種方法詳解

    Spring實(shí)現(xiàn)定時(shí)任務(wù)的兩種方法詳解

    Spring提供了兩種方式實(shí)現(xiàn)定時(shí)任務(wù),一種是注解,還有一種就是接口了,這篇文章主要為大家介紹了這兩種方法的具體實(shí)現(xiàn)方法,需要的可以參考下
    2024-12-12
  • Java中的RestTemplate使用詳解

    Java中的RestTemplate使用詳解

    這篇文章主要介紹了Java中的RestTemplate使用詳解,Spring內(nèi)置了RestTemplate作為Http請(qǐng)求的工具類,簡(jiǎn)化了很多操作,雖然Spring5推出了WebClient,但是整體感覺還是RestTemplate用起來更簡(jiǎn)單方便一些,需要的朋友可以參考下
    2023-10-10
  • java Thread 多線程

    java Thread 多線程

    本篇文章小編為大家介紹,java Thread 多線程。需要的朋友參考下
    2013-04-04

最新評(píng)論

宝清县| 无锡市| 石棉县| 晋州市| 兰西县| 曲松县| 镇巴县| 遂昌县| 长泰县| 呈贡县| 罗江县| 东安县| 拜泉县| 西安市| 镇雄县| 长沙县| 定结县| 正阳县| 大邑县| 永德县| 汉源县| 上高县| 怀集县| 海阳市| 鄂州市| 大竹县| 文登市| 临澧县| 天镇县| 深圳市| 米易县| 界首市| 德州市| 灵寿县| 莒南县| 楚雄市| 苏尼特右旗| 靖州| 墨玉县| 聂荣县| 广灵县|