如何配置mybatisplus不区分大小写
时间: 2023-07-04 13:16:39 浏览: 231
MybatisPlus 默认是区分大小写的,如果要实现不区分大小写的查询,可以在 MybatisPlus 的配置文件中添加一个全局拦截器,使用拦截器拦截 SQL,将 SQL 中的表名和列名转换为小写,然后再执行 SQL。
具体实现步骤如下:
1. 创建一个拦截器类,实现 MybatisPlus 的拦截器接口 Interceptor,重写其 intercept 方法,如下所示:
```
public class CaseInsensitiveInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = statement.getBoundSql(parameter);
String sql = boundSql.getSql().toLowerCase();
sql = sql.replaceAll("\\bfrom\\b", "FROM");
sql = sql.replaceAll("\\bselect\\b", "SELECT");
sql = sql.replaceAll("\\bwhere\\b", "WHERE");
sql = sql.replaceAll("\\band\\b", "AND");
sql = sql.replaceAll("\\bor\\b", "OR");
sql = sql.replaceAll("\\bgroup by\\b", "GROUP BY");
sql = sql.replaceAll("\\bhaving\\b", "HAVING");
sql = sql.replaceAll("\\border by\\b", "ORDER BY");
boundSql = new BoundSql(statement.getConfiguration(), sql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement newStatement = copyFromMappedStatement(statement, boundSql);
invocation.getArgs()[0] = newStatement;
return invocation.proceed();
}
private MappedStatement copyFromMappedStatement(MappedStatement ms, BoundSql boundSql) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(),
ms.getId(), boundSql, 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.cache(ms.getCache());
builder.useCache(ms.isUseCache());
return builder.build();
}
}
```
2. 在 MybatisPlus 的配置文件中添加该拦截器,如下所示:
```
mybatis-plus:
configuration:
# 添加拦截器
interceptors:
- com.example.demo.CaseInsensitiveInterceptor
```
通过以上步骤,就可以实现 MybatisPlus 不区分大小写的查询了。
阅读全文