SQL server使用MybatisPlus查询SQL加上WITH (NOLOCK)

文章目录

  • [WITH (NOLOCK) 是什么?](#WITH (NOLOCK) 是什么?)
  • 代码示例

WITH (NOLOCK) 是什么?

WITH (NOLOCK) 也叫 未提交读(READ UNCOMMITTED),是 SQL Server 中的一种表提示(Table Hint),本质是让查询语句忽略目标表上的共享锁和排他锁,直接读取数据,核心目的是提升查询性能、避免查询被阻塞。

SQL Server 默认的隔离级别是 READ COMMITTED(已提交读),即查询会等待目标数据上的锁释放后再读取,且只能读取已提交的数据;而 NOLOCK 会强制查询使用 READ UNCOMMITTED 隔离级别,打破这个规则。

代码示例

java 复制代码
package com.qf.config;


import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class MybatisPlusSqlInterceptor implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        // 先判断是不是SELECT操作 不是直接跳过
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        String id = mappedStatement.getId();
        String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
        //只有Mybatis plus的selectOne和selectList做特殊处理
        if (!methodName.equals("selectOne") && !methodName.equals("selectList") && !methodName.equals("selectMaps")) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        // 执行的SQL语句
        String originalSql = boundSql.getSql().replace("\n", "");
        String tableName = extractFromClause(originalSql);
        log.info("要执行的sql:{}", originalSql);
        log.info("正则表达式获取要执行的sql的表名:{}", tableName);
        if (StringUtils.isNotEmpty(tableName)) {
            String finalSql = originalSql.replace(tableName, tableName + " WITH(NOLOCK)");
            log.info("处理后的sql:{}", finalSql);
            metaObject.setValue("delegate.boundSql.sql", finalSql);
        }
        return invocation.proceed();
    }

    public static String extractFromClause(String query) {
        String table = "";
        Pattern p = Pattern.compile("FROM \\[(.*?)\\]");
        Matcher m = p.matcher(query);
        if (m.find()) {
            table = m.group();
        }
        return table.trim();
    }
}

相关推荐
Hrain-AI7 小时前
多 Agent 并行不打架:worktree 隔离与反馈回流落地(附脚本)
网络·数据库·人工智能·架构
净水深流8 小时前
中央厨房冷链技术实践:多温区改造、WMS落地与IoT温控架构
大数据·数据库·人工智能·冷库冷链
l1t8 小时前
测试DuckDB 2.1的match_recognize模式匹配语句
数据库·duckdb
IpdataCloud9 小时前
AI智能体调用工具怎么核验来源IP?归属地、网络类型与代理风险识别(含Python代码)
数据库·python·tcp/ip
曹牧9 小时前
Java:SQL 注入漏洞
数据库
程序员JerrySUN10 小时前
Jetson Edge AI 实战01:Nano、Xavier、Orin 怎么选?Jetson 硬件选型详解【视频讲解】
java·数据库·redis·安全·mybatis
oradh10 小时前
Oracle Undo问题总结(ORA-600 [4xxx] 系列错误)
数据库·oracle
达梦数据10 小时前
DMDRS辅助表生成规则与作用
数据库·oracle
‎ദ്ദിᵔ.˛.ᵔ₎10 小时前
MySQL 表约束
数据库·mysql
Doris__HE10 小时前
【元脑服务器NF5476G7-NF5476M7技术规格分享】
运维·服务器·网络·数据库·性能优化