MyBatis模糊查询的三种处理参数方式

1.${}
    直接拼接 '%${参数名}%'   这种方法不推荐,有SQL注入的风险
2.#{}
    在传参的时候进行拼接 " '%'+参数+'%' " 
3.bind标签
    对传过来的参数进行处理

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis是一个开源的持久层框架,它可以助开发者简化数据库操作。MyBatis提供了一个拦截器(Interceptor)的机制,可以在SQL执行过程中进行拦截和处理。 在MyBatis中进行模糊查询时,可以使用拦截器来实现。拦截器可以在SQL语句执行前后对参数进行处理,从而实现模糊查询的功能。 下面是一个简单的示例,展示如何使用MyBatis拦截器实现模糊查询: 1. 创建一个实现了Interceptor接口的拦截器类,例如FuzzyQueryInterceptor。 ```java public class FuzzyQueryInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 获取原始的SQL语句和参数 MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = invocation.getArgs()[1]; BoundSql boundSql = mappedStatement.getBoundSql(parameter); String sql = boundSql.getSql(); // 对SQL语句进行处理,将模糊查询参数加上通配符 String fuzzyParam = "%" + parameter.toString() + "%"; sql = sql.replace("#{param}", fuzzyParam); BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject()); // 将新的BoundSql设置回原始的MappedStatement MappedStatement newMappedStatement = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql)); invocation.getArgs()[0] = newMappedStatement; // 继续执行原始的SQL语句 return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // 可以在这里设置一些属性 } 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()); builder.keyProperty(StringUtils.join(ms.getKeyProperties(), ",")); builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.cache(ms.getCache()); return builder.build(); } private static class BoundSqlSqlSource implements SqlSource { private final BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } @Override public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } } ``` 2. 在MyBatis的配置文件中配置拦截器。 ```xml <configuration> <plugins> <plugin interceptor="com.example.FuzzyQueryInterceptor"/> </plugins> </configuration> ``` 通过以上步骤,就可以在MyBatis中使用拦截器来实现模糊查询的功能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

codewen77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值