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();
    }
}

相关推荐
IvorySQL9 小时前
PostgreSQL 日报|修复截断 zstd 备份检测(10 月 9 日)
数据库·postgresql
刘胡子大叔9 小时前
SQL 脚本的导入顺序
数据库·sql
代码什么用10 小时前
Spring对IoC的实现
数据库·spring
hz5678912 小时前
涉密视频会议设备配置指南:终端、音视频采集与配套设施选型
服务器·网络·数据库·安全·实时音视频·信息与通信·智能硬件
广州浮点FLOATLIC12 小时前
许可证服务器迁移后软件打不开:研发 IT 怎样定位连接问题
linux·服务器·数据库
程序员Sunday12 小时前
MySQL 为什么使用 B+ 树索引?把范围查询、回表和覆盖索引连起来
数据库·mysql
半杯咖啡半行码12 小时前
Qt开发实战:数据库、MV 模式、QProcess与串口通信全攻略
数据库·qt
Yyyyyy~12 小时前
[ Mysql ] 库的操作
mysql
小米里的大麦13 小时前
16 MySQL 事务
数据库·mysql
西柚小萌新13 小时前
【LLM&&AI应用开发 八股文】--4.3.Agent智能体(下)
java·开发语言·数据库