Skip to content
广告❤️成为赞助商

替换器

替换器,会在MongoPlus执行增删改查时,经过替换器,可以将删除方法替换为更新方法,⚠️执行首个命中执行器

说明:

  • 使用替换器时,需要将其注册为SpringBean

com.anwen.mongo.replacer.Replacer

  • 该接口是替换器的接口,所有替换器都应实现此接口,并实现接口
java
public interface Replacer {

    default int order() {
        return Integer.MIN_VALUE;
    }

    /**
     * 执行的方法
     */
    Object invoke(Object proxy, Object target, Method method, Object[] args) throws Throwable;

    /**
     * 是否可以执行
     */
    BoolFunction supplier();

}

示例

首先,需要将替换器类实现Replacer接口,并将该类注册为Bean
java
//注册为SpringBean
@Component
public class CustomReplacer implements Replacer {}
接下来,Replacer接口中的方法,将物理删除替换为逻辑删除,⚠️需要将返回值转为原本方法的返回值类型
java
//注册为SpringBean
@Component
public class CustomReplacer implements Replacer {

 @Override
    public Object invoke(Object proxy, Object target, Method method, Object[] args) throws Throwable {

        Class<?> clazz = LogicDeleteHandler.getBeanClass((MongoCollection<Document>) args[1]);
        if (Objects.isNull(clazz)) {
            return method.invoke(target, args);
        }
        LogicDeleteResult result = LogicDeleteHandler.mapper().get(clazz);
        if (Objects.isNull(result)) {
            return method.invoke(target, args);
        }
        Method updateMethod = target.getClass().getMethod(ExecuteMethodEnum.UPDATE.getMethod(), Bson.class, Bson.class, MongoCollection.class);
        Document updateBasic = new Document(result.getColumn(), result.getLogicDeleteValue());
        BasicDBObject update = new BasicDBObject(SpecialConditionEnum.SET.getCondition(), updateBasic);
        Object[] updateArgs = new Object[]{args[0], update, args[1]};
        UpdateResult res = (UpdateResult) updateMethod.invoke(target, updateArgs);
        // 替换回原本删除需要的返回值 避免类型转换错误
        return new DeleteResult() {
            @Override
            public boolean wasAcknowledged() {
                return res.wasAcknowledged();
            }

            @Override
            public long getDeletedCount() {
                return res.getModifiedCount();
            }
        };

    }

    @Override
    public BoolFunction supplier() {
        return (proxy, target, method, args) -> CollectionLogicDeleteCache.open && method.getName().equals(ExecuteMethodEnum.REMOVE.getMethod());
    }
    
}