In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to implement MyBatis custom SQL interceptor", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to implement a custom SQL interceptor for MyBatis.
Define whether to turn on annotations
To define whether to turn on annotations, one of the main things to do is whether to add an SQL interceptor.
/ / globally open @ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.TYPE) @ Documented@Import (MyBatisSqlInterceptorConfiguration.class) public @ interface EnableSqlInterceptor {} / / Custom comments @ Target ({ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface DataScope {} register SQL interceptor
Registering a SQL interceptor will intercept eligible SQL query operations.
Public class MyBatisSqlInterceptorConfiguration implements ApplicationContextAware {@ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {SqlSessionFactory sqlSessionFactory = applicationContext.getBean (SqlSessionFactory.class); sqlSessionFactory.getConfiguration () .addInterceptor (new MyBatisInterceptor ());}} processing logic
In the processing logic, I mainly do a simple limit 1 case, if I need to do other logic needs to modify
Slf4j@Intercepts ({@ Signature (type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @ Signature (type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}) }) public class MyBatisInterceptor implements Interceptor {private static final Logger LOGGER = LoggerFactory.getLogger (MyBatisInterceptor.class) @ Override public Object intercept (Invocation invocation) throws Throwable {/ / TODO Auto-generated method stub Object [] args = invocation.getArgs (); MappedStatement ms = (MappedStatement) args [0]; Object parameter = args [1]; RowBounds rowBounds = (RowBounds) args [2]; ResultHandler resultHandler = (ResultHandler) args [3]; Executor executor = (Executor) invocation.getTarget (); CacheKey cacheKey; BoundSql boundSql / / due to logic, only once if (args.length = = 4) {/ / 4 parameters boundSql = ms.getBoundSql (parameter); cacheKey = executor.createCacheKey (ms, parameter, rowBounds, boundSql);} else {/ / 6 parameters cacheKey = (CacheKey) args [4] BoundSql = (BoundSql) args [5];} DataScope dataScope = getDataScope (ms); if (Objects.nonNull (dataScope)) {String origSql = boundSql.getSql (); log.info ("origSql: {}", origSql); / / assemble new sql / / todo you weaving business String newSql = origSql + "limit 1" / / re-new a query statement object BoundSql newBoundSql = newBoundSql (ms.getConfiguration (), newSql, boundSql.getParameterMappings (), boundSql.getParameterObject ()); / / put the new query in statement MappedStatement newMs = newMappedStatement (ms, new BoundSqlSource (newBoundSql)) For (ParameterMapping mapping: boundSql.getParameterMappings ()) {String prop = mapping.getProperty (); if (boundSql.hasAdditionalParameter (prop)) {newBoundSql.setAdditionalParameter (prop, boundSql.getAdditionalParameter (prop));} args [0] = newMs If (args.length = = 6) {args [5] = newMs.getBoundSql (parameter);}} LOGGER.info ("mybatis intercept sql: {}, Mapper method is: {}", boundSql.getSql (), ms.getId ()); return invocation.proceed () } private MappedStatement newMappedStatement (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 & & ms.getKeyProperties (). Length > 0) {builder.keyProperty (ms.getKeyProperties () [0]);} builder.timeout (ms.getTimeout ()); builder.parameterMap (ms.getParameterMap ()); builder.resultMaps (ms.getResultMaps ()); builder.resultSetType (ms.getResultSetType ()); builder.cache (ms.getCache ()) Builder.flushCacheRequired (ms.isFlushCacheRequired ()); builder.useCache (ms.isUseCache ()); return builder.build ();} private DataScope getDataScope (MappedStatement mappedStatement) {String id = mappedStatement.getId (); / / get Class Method String clazzName = id.substring (0, id.lastIndexOf ('.)); String mapperMethod = id.substring (id.lastIndexOf ('.) + 1); Class clazz Try {clazz = Class.forName (clazzName);} catch (ClassNotFoundException e) {return null;} Method [] methods = clazz.getMethods (); DataScope dataScope = null; for (Method method: methods) {if (method.getName (). Equals (mapperMethod)) {dataScope = method.getAnnotation (DataScope.class) Break;}} return dataScope;} @ Override public Object plugin (Object target) {/ / TODO Auto-generated method stub LOGGER.info ("MysqlInterCeptor plugin > {}", target); return Plugin.wrap (target, this) } @ Override public void setProperties (Properties properties) {/ / TODO Auto-generated method stub String dialect = properties.getProperty ("dialect"); LOGGER.info ("mybatis intercept dialect: > {}", dialect);} / * define an internal helper class that wraps SQL * / class BoundSqlSource implements SqlSource {private BoundSql boundSql Public BoundSqlSource (BoundSql boundSql) {this.boundSql = boundSql;} public BoundSql getBoundSql (Object parameterObject) {return boundSql;}} how to use
We only need to add the @ DataScope annotation to the corresponding data manipulation method in XXXMapper.
@ Mapperpublic interface OrderMapper {@ Select ("select 1") @ DataScope Intger selectOne (); at this point, I believe you have a better understanding of "how to implement MyBatis custom SQL interceptor". You might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.