001/* 002 * Copyright (c) 2022-2023, 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.logicdelete; 017 018import com.mybatisflex.core.logicdelete.impl.DefaultLogicDeleteProcessor; 019 020import java.util.function.Supplier; 021 022/** 023 * 逻辑删除管理器。 024 */ 025public class LogicDeleteManager { 026 027 private LogicDeleteManager() { 028 } 029 030 private static LogicDeleteProcessor processor = new DefaultLogicDeleteProcessor(); 031 private static final ThreadLocal<Boolean> skipFlags = new ThreadLocal<>(); 032 033 /** 034 * 获取逻辑删除处理器。 035 * 036 * @return 逻辑删除处理器 037 */ 038 public static LogicDeleteProcessor getProcessor() { 039 return processor; 040 } 041 042 /** 043 * 设置逻辑删除处理器。 044 * 045 * @param processor 逻辑删除处理器 046 */ 047 public static void setProcessor(LogicDeleteProcessor processor) { 048 LogicDeleteManager.processor = processor; 049 } 050 051 /** 052 * 跳过逻辑删除字段处理,直接进行数据库物理操作。 053 */ 054 public static <T> T execWithoutLogicDelete(Supplier<T> supplier) { 055 try { 056 skipLogicDelete(); 057 return supplier.get(); 058 } finally { 059 restoreLogicDelete(); 060 } 061 } 062 063 /** 064 * 跳过逻辑删除字段处理,直接进行数据库物理操作。 065 */ 066 public static void execWithoutLogicDelete(Runnable runnable) { 067 try { 068 skipLogicDelete(); 069 runnable.run(); 070 } finally { 071 restoreLogicDelete(); 072 } 073 } 074 075 /** 076 * 跳过逻辑删除字段处理。 077 */ 078 public static void skipLogicDelete() { 079 skipFlags.set(Boolean.TRUE); 080 } 081 082 /** 083 * 恢复逻辑删除字段处理。 084 */ 085 public static void restoreLogicDelete() { 086 skipFlags.remove(); 087 } 088 089 /** 090 * 获取逻辑删除列,返回 {@code null} 表示跳过逻辑删除。 091 * 092 * @param logicDeleteColumn 逻辑删除列 093 * @return 逻辑删除列 094 */ 095 public static String getLogicDeleteColumn(String logicDeleteColumn) { 096 if (logicDeleteColumn == null) { 097 return null; 098 } 099 Boolean skipFlag = skipFlags.get(); 100 if (skipFlag == null) { 101 return logicDeleteColumn; 102 } 103 return skipFlag ? null : logicDeleteColumn; 104 } 105 106}