一、环境信息
SpringBoot:2.3.6.RELEASE
Mybatis-plus:3.3.1
二、碰到问题
明天因业务零碎性能须要,应用mybatis的拦截器对ORACLE的数据库会话进行用户以后语言环境设置(NLS_LANGUAGE),碰到拦截器代码不失效的问题,特此记录下来,不便未来查阅。
三、代码如下:
1、在Mybatis的@Configuration相干代码增加如下代码(主动注入到拦截器链):
/** * 更改会话状态 * * @return */@Beanpublic AlterSessionInterceptor alterSessionInterceptor() { return new AlterSessionInterceptor();}
2、拦截器代码(拦挡StatementHandler的prepare办法,取到Connection执行ALTER SESSION的语句):
/**
- <p>
- 更改会话解析器
- </p>
* - @since 2021/7/14
*/
@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class AlterSessionInterceptor implements Interceptor {
@Overridepublic Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); Connection connection = (Connection) args[0]; if ("Oracle".equalsIgnoreCase(connection.getMetaData().getDatabaseProductName())) { Statement statement = null; try { statement = connection.createStatement(); String locale = RequestHelper.getCurrentLocale(); if ("en_GB".equalsIgnoreCase(locale)) { statement.execute("ALTER SESSION SET NLS_LANGUAGE='AMERICAN'"); } else { statement.execute("ALTER SESSION SET NLS_LANGUAGE='SIMPLIFIED CHINESE'"); } } finally { statement.close(); } } return invocation.proceed();}
}
在运行调试时发现代码无奈执行到拦挡逻辑,通过参考分页插件代码,发现须要重载以下办法(代码默认是只有实现intercept这个接口,然而实际上须要多加以下插件的解决逻辑才能够,才会启用Plugin的Proxy):
@Overridepublic Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } return target;}
最终拦截器代码如下:
/**
- <p>
- 更改会话解析器
- </p>
* - @since 2021/7/14
*/
@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class AlterSessionInterceptor implements Interceptor {
@Overridepublic Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); Connection connection = (Connection) args[0]; if ("Oracle".equalsIgnoreCase(connection.getMetaData().getDatabaseProductName())) { Statement statement = null; try { statement = connection.createStatement(); String locale = RequestHelper.getCurrentLocale(); if ("en_GB".equalsIgnoreCase(locale)) { statement.execute("ALTER SESSION SET NLS_LANGUAGE='AMERICAN'"); } else { statement.execute("ALTER SESSION SET NLS_LANGUAGE='SIMPLIFIED CHINESE'"); } } finally { statement.close(); } } return invocation.proceed();}@Overridepublic Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } return target;}@Overridepublic void setProperties(Properties properties) { // to do nothing}
}