001/* 002 * Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.optimisticlock; 017 018import java.util.function.Supplier; 019 020/** 021 * 乐观锁管理器。 022 */ 023public class OptimisticLockManager { 024 025 private OptimisticLockManager() { 026 } 027 028 private static final ThreadLocal<Boolean> skipFlags = new ThreadLocal<>(); 029 030 /** 031 * 跳过乐观锁字段处理,直接进行数据库物理操作。 032 */ 033 public static <T> T execWithoutOptimisticLock(Supplier<T> supplier) { 034 try { 035 skipOptimisticLock(); 036 return supplier.get(); 037 } finally { 038 restoreOptimisticLock(); 039 } 040 } 041 042 /** 043 * 跳过乐观锁字段处理,直接进行数据库物理操作。 044 */ 045 public static void execWithoutOptimisticLock(Runnable runnable) { 046 try { 047 skipOptimisticLock(); 048 runnable.run(); 049 } finally { 050 restoreOptimisticLock(); 051 } 052 } 053 054 /** 055 * 跳过乐观锁字段处理。 056 */ 057 public static void skipOptimisticLock() { 058 skipFlags.set(Boolean.TRUE); 059 } 060 061 /** 062 * 恢复乐观锁字段处理。 063 */ 064 public static void restoreOptimisticLock() { 065 skipFlags.remove(); 066 } 067 068 /** 069 * 获取乐观锁列,返回 {@code null} 表示跳过乐观锁。 070 * 071 * @param optimisticLockColumn 乐观锁列 072 * @return 乐观锁列 073 */ 074 public static String getOptimisticLockColumn(String optimisticLockColumn) { 075 if (optimisticLockColumn == null) { 076 return null; 077 } 078 Boolean skipFlag = skipFlags.get(); 079 if (skipFlag == null) { 080 return optimisticLockColumn; 081 } 082 return skipFlag ? null : optimisticLockColumn; 083 } 084 085}