mybatis操作Oracle数据库如何指定NLS_LANGUAGE多语言

一、背景
笔者碰到应用系统连接Oracle数据库时多语言需要统一使用英语,该配置不能在数据库Server端修改,因些需要在应用系统端想办法进行配置。
二、解决方式
经过查阅数据源和mybatis相关源码,有两种方式支持修改:
1、使用Druid数据源的配置项connectionInitSqls定义连接初始化语句:
connectionInitSqls: ["ALTER SESSION SET NLS_LANGUAGE='AMERICAN'"]
2、不修改数据源配置,在应用系统端增加mybatis的拦截器,拦截器代码如下:
(1)、Spring boot的Bean配置
@Configuration
public class MybatisPlusConfig {

/** * 更改会话状态 * * @return */ @Bean public AlterSessionInterceptor alterSessionInterceptor() { return new AlterSessionInterceptor(); }/** * 乐观锁插件 * * @return */ @Bean public CustomOptimisticLockerInterceptor optimisticLockerInterceptor() { return new CustomOptimisticLockerInterceptor(); }/** * oracle Sequence主键 * * @return */ @Bean public OracleKeyGenerator oracleKeyGenerator() { return new OracleKeyGenerator(); }

}
(2)、拦截器代码:
@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class AlterSessionInterceptor implements Interceptor {
@Override public 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(); }@Override public Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } return target; }@Override public void setProperties(Properties properties) { // to do nothing }

【mybatis操作Oracle数据库如何指定NLS_LANGUAGE多语言】三、方案对比
1、在数据源配置,一次性配置,不用修改代码,所有用户都全部看到的错误信息全部都是英文提示
2、在代码进行拦截处理,需要修改代码,可针对不同的用户显示不同语言版本的错误提示,但是每次执行语句时,都须要多执行一句设置语言版本语句,操作繁琐,影响性能

    推荐阅读