关联表更新封装

简介: 关联表更新封装

凭自己的本事和正当手段挣来的钱财,可以使我们赢得道义和幸福——阿基兰

分享一个关联更新函数

package com.ruben.simplestreamquery.util;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ruben.simplestreamquery.pojo.bo.RelationBO;
import io.github.vampireachao.stream.core.bean.BeanHelper;
import io.github.vampireachao.stream.core.lambda.LambdaExecutable;
import io.github.vampireachao.stream.core.lambda.LambdaHelper;
import io.github.vampireachao.stream.core.lambda.function.SerSupp;
import io.github.vampireachao.stream.core.reflect.ReflectHelper;
import io.github.vampireachao.stream.core.stream.Steam;
import io.github.vampireachao.stream.plugin.mybatisplus.Database;
import io.github.vampireachao.stream.plugin.mybatisplus.Many;
import lombok.val;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import static cn.hutool.core.text.CharSequenceUtil.genSetter;
import static java.util.Collections.emptyList;
/**
 * MpUtil
 *
 * @author VampireAchao
 * @since 2023/3/15
 */
public class MpUtil {
    public static <T,
            K extends Comparable<? super K> & Serializable,
            A,
            U extends Comparable<? super U> & Serializable,
            R> BaseDbBO<R> saveRelation(RelationBO<T, K, A, U, R> bo) {
        val mainList = bo.getMainList();
        val mainKeys = Steam.of(mainList).map(bo.getMainKey()).toList();
        val relationMainGetter = LambdaHelper.resolve(bo.getRelationMain());
        val relationMainSetter = getSetter(bo.getRelationMain());
        val relationAttachSetter = getSetter(bo.getRelationAttach());
        val relationClass = (Class<?>) relationMainGetter.getInstantiatedTypes()[0];
        val constructor = ((SerSupp<Constructor<?>>) relationClass::getConstructor).get();
        val constructorLambda = LambdaHelper.revert(Supplier.class, constructor);
        val nameRelationCompareSetterMap = Steam.of(bo.getRelationCompares())
                .map(c -> LambdaHelper.resolve((Serializable) c))
                .<String, BiConsumer<R, Object>>toMap(LambdaExecutable::getName, MpUtil::getSetter);
        val willInsertList = Steam.of(mainList).flatMap(vo -> Steam.of(bo.getAttachGetter().apply(vo)))
                .filter(bo.getAttachKey(), null)
                .toList();
        if (!willInsertList.isEmpty()) {
            if (bo.getInsertOnMissAttach()) {
                Database.saveFewSql(willInsertList);
            } else {
                throw new IllegalStateException("attach data missing");
            }
        }
        val relationsFromClient = Steam.of(mainList)
                .flatMap(vo -> Steam.of(bo.getAttachGetter().apply(vo))
                        .map(attach -> {
                            R relation = (R) constructorLambda.get();
                            relationMainSetter.accept(relation, bo.getMainKey().apply(vo));
                            relationAttachSetter.accept(relation, bo.getAttachKey().apply(attach));
                            Steam.of(bo.getAttachCompares()).forEach(c -> {
                                val executable = LambdaHelper.resolve((Serializable) c);
                                val setter = nameRelationCompareSetterMap.get(executable.getName());
                                setter.accept(relation, c.apply(attach));
                            });
                            return relation;
                        })
                ).toList();
        val relationMain = bo.getRelationMain();
        val relationsFromDb = Many.of(relationMain).in(mainKeys).query();
        if (relationsFromClient.isEmpty()) {
            bo.setWillDeleteList(relationsFromDb);
            return bo;
        }
        if (relationsFromDb.isEmpty()) {
            bo.setWillInsertList(relationsFromClient);
            bo.setDataList(relationsFromClient);
            return bo;
        }
        val mainIdRelationsMapFromDb = Steam.of(relationsFromDb)
                .group(relationMain);
        val mainIdRelationsMapFromClient = Steam.of(relationsFromClient)
                .group(relationMain);
        mainKeys.forEach(mainKey -> {
            val relationListFromDb = mainIdRelationsMapFromDb.getOrDefault(mainKey, emptyList());
            val relationListFromClient = mainIdRelationsMapFromClient.getOrDefault(mainKey, emptyList());
            if (relationListFromDb.isEmpty() && relationListFromClient.isEmpty()) {
                return;
            }
            if (relationListFromDb.isEmpty()) {
                bo.getWillInsertList().addAll(relationListFromClient);
                return;
            }
            if (relationListFromClient.isEmpty()) {
                bo.getWillDeleteList().addAll(relationListFromDb);
                return;
            }
            val attachKeyRelationMapFromClient = Steam.of(relationListFromClient)
                    .toMap(bo.getRelationAttach());
            val attachKeysFromClient = attachKeyRelationMapFromClient.keySet();
            val attachKeyRelationMapFromDb = Steam.of(relationListFromDb)
                    .toMap(bo.getRelationAttach());
            val attachKeysFromDb = attachKeyRelationMapFromDb.keySet();
            // insert
            Steam.of(attachKeysFromClient).filter(attachKey -> !attachKeysFromDb.contains(attachKey))
                    .map(attachKeyRelationMapFromClient::get)
                    .forEach(bo.getWillInsertList()::add);
            // remove
            Steam.of(attachKeysFromDb).filter(attachKey -> !attachKeysFromClient.contains(attachKey))
                    .map(attachKeyRelationMapFromDb::get)
                    .forEach(bo.getWillDeleteList()::add);
            // modify
            attachKeysFromDb.retainAll(attachKeysFromClient);
            attachKeysFromDb.forEach(attachKey -> {
                val relationFromDb = attachKeyRelationMapFromDb.get(attachKey);
                val relationFromClient = attachKeyRelationMapFromClient.get(attachKey);
                if (Objects.nonNull(relationFromDb) && Objects.nonNull(relationFromClient)) {
                    Steam.of(bo.getRelationCompares()).forEach(ac -> {
                        val value = ac.apply(relationFromClient);
                        if (!Objects.equals(value, ac.apply(relationFromDb))) {
                            val executable = LambdaHelper.resolve((Serializable) ac);
                            val setter = nameRelationCompareSetterMap.get(executable.getName());
                            setter.accept(relationFromDb, value);
                            if (!bo.getWillUpdateList().contains(relationFromDb)) {
                                bo.getWillUpdateList().add(relationFromDb);
                            }
                        }
                    });
                }
            });
        });
        bo.setAfterExecuted(b -> {
            val relationPrimaryKey = MpUtil.getGetter((Class<R>) relationClass,
                    TableInfoHelper.getTableInfo(relationClass).getKeyProperty());
            relationsFromDb.removeIf(bo.getWillDeleteList()::contains);
            relationsFromDb.addAll(bo.getWillInsertList());
            val idAttachMap = Steam.of(relationsFromDb).toMap(relationPrimaryKey);
            relationsFromClient.forEach(data -> {
                val pk = relationPrimaryKey.apply(data);
                idAttachMap.put(pk, data);
            });
            bo.setDataList(new ArrayList<>(idAttachMap.values()));
        });
        return bo;
    }
    public static <T, R> SFunction<T, R> getGetter(Class<T> clazz, String property) {
        return LambdaHelper.revert(
                SFunction.class,
                ReflectHelper.getMethod(
                        clazz,
                        StrUtil.genGetter(property)
                )
        );
    }
    public static <T, R> BiConsumer<T, R> getSetter(SFunction<T, R> getter) {
        return getSetter(LambdaHelper.resolve(getter));
    }
    public static <T, R> BiConsumer<T, R> getSetter(LambdaExecutable executable) {
        val setterName = genSetter(BeanHelper.getPropertyName(executable.getName()));
        val setter = Steam.of(ReflectHelper.getMethods(executable.getClazz()))
                .findFirst(m -> m.getName().equals(setterName))
                .orElse(null);
        return LambdaHelper.revert(BiConsumer.class, setter);
    }
}


用到的bo

import io.github.vampireachao.stream.core.lambda.function.SerCons;
import io.github.vampireachao.stream.plugin.mybatisplus.Database;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
 * @author VampireAchao
 * @since 2023/3/16 11:07
 */
@Data
public abstract class BaseDbBO<T> {
    private List<T> willInsertList;
    private List<T> willDeleteList;
    private List<T> willUpdateList;
    private List<T> dataList;
    private Consumer<BaseDbBO<T>> afterExecuted;
    public BaseDbBO() {
        dataList = new ArrayList<>();
        willInsertList = new ArrayList<>();
        willDeleteList = new ArrayList<>();
        willUpdateList = new ArrayList<>();
        afterExecuted = SerCons.nothing();
    }
    public List<T> execute() {
        Database.removeByIds(getWillDeleteList());
        Database.saveFewSql(getWillInsertList());
        Database.updateFewSql(getWillUpdateList());
        afterExecuted.accept(this);
        return dataList;
    }
    public BaseDbBO<T> add(BaseDbBO<T> bo) {
        this.getWillInsertList().addAll(bo.getWillInsertList());
        this.getWillDeleteList().addAll(bo.getWillDeleteList());
        this.getWillUpdateList().addAll(bo.getWillUpdateList());
        this.afterExecuted = SerCons.multi(this.afterExecuted::accept, bo.getAfterExecuted()::accept);
        return this;
    }
}

使用方式:

MpUtil.saveRelation(new RelationBO<RuleParamVO, Integer, PositionVO, String, PositionRule>() {{
    setMainList(rules);
    setMainKey(RuleParamVO::getId);
    setAttachKey(PositionVO::getPositionId);
    setAttachGetter(RuleParamVO::getPositions);
    setRelationMain(PositionRule::getRuleId);
    setRelationAttach(PositionRule::getPositionId);
}}).execute();
MpUtil.saveRelation(new RelationBO<RuleParamVO, Integer, SysDepartVO, String, DepartRuleParam>() {{
    setMainList(rules);
    setMainKey(RuleParamVO::getId);
    setAttachKey(SysDepartVO::getDepartId);
    setAttachGetter(RuleParamVO::getDepartments);
    setRelationMain(DepartRuleParam::getRuleParamId);
    setRelationAttach(DepartRuleParam::getDepartmentId);
}});
MpUtil.saveRelation(new RelationBO<RuleParamVO, Integer, PositionVO, String, MemberRule>() {{
    setMainList(rules);
    setMainKey(RuleParamVO::getId);
    setAttachKey(PositionVO::getPositionId);
    setAttachGetter(RuleParamVO::getMembers);
    setRelationMain(MemberRule::getRuleId);
    setRelationAttach(MemberRule::getPositionId);
}});
MpUtil.saveRelation(new RelationBO<RuleParamVO, Integer, StageVO, Integer, RuleStageParam>() {{
    setMainList(rules);
    setMainKey(RuleParamVO::getId);
    setAttachKey(StageVO::getStageId);
    setAttachGetter(RuleParamVO::getStages);
    setRelationMain(RuleStageParam::getRuleParamId);
    setRelationAttach(RuleStageParam::getStageId);
}});
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
 * @author VampireAchao
 * @since 2023/3/6 11:32
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class RelationBO<T,
        K extends Comparable<? super K> & Serializable,
        A,
        U extends Comparable<? super U> & Serializable,
        R> extends BaseDbBO<R> {
    private List<T> mainList;
    private SFunction<T, K> mainKey;
    private SFunction<A, U> attachKey;
    private SFunction<T, List<A>> attachGetter;
    private SFunction<R, K> relationMain;
    private SFunction<R, U> relationAttach;
    private List<SFunction<A, Object>> attachCompares;
    private List<SFunction<R, Object>> relationCompares;
    private Boolean insertOnMissAttach;
    public RelationBO() {
        super();
        attachCompares = new ArrayList<>();
        relationCompares = new ArrayList<>();
        insertOnMissAttach = false;
    }
}

相关解释如下:

相关文章
|
移动开发 前端开发 Java
《钉钉应用开发者速成手册》之“钉钉应用开发入门——H5微应用”
本文将以获取当前用户部门信息的H5微应用为例,帮助您快速了解钉钉H5微应用的开发流程。
4457 0
《钉钉应用开发者速成手册》之“钉钉应用开发入门——H5微应用”
|
数据采集 人工智能 自然语言处理
1小时让AI员工“上岗接活”:AI实训营活动落地北京城市副中心,云大使专属服务赋能创业者
阿里云云大使深度参与临河里街道曦光OPC创业社区的AI普及实践,通过“专家授课+实操演练+资源对接”模式,帮助从业者快速掌握Qoder系列智能体在文档生成、数据清洗、跨系统协同等场景的落地应用技巧,并为参会者提供专属权益与产品咨询服务,依托阿里云丰富的产品生态与专业服务能力,赋能开发者与推广者,共享 AI 时代发展红利。
1小时让AI员工“上岗接活”:AI实训营活动落地北京城市副中心,云大使专属服务赋能创业者
|
5月前
|
人工智能 自然语言处理 监控
开源生态构建:从6个GitHub仓库到金融AI工具链
开源金融AI技能库:56个场景全覆盖 实战代码:基于 financial-ai-skills 项目 | 开源生态 | 场景覆盖 | 贡献指南 项目概览 `` financial-ai-skills/ ├── README.md ├── LICENSE (MIT) ├── skills/ │ ├── financial-intelligence/ # 财务智能 (8个场景) │ ├──
|
5月前
|
人工智能 文字识别 并行计算
离谱!我以为 OCR 还在一页页抠字,结果百度 1.2 万 Star Unlimited-OCR 直接把长文档一口气读完
百度开源 Unlimited-OCR,把图片、长文档、多页 PDF 这类非结构化资料推进到 Markdown、表格和可检索文本,适合 RAG、知识库和 Agent 文档入口。
579 7
|
5月前
|
人工智能 自然语言处理 安全
Agent Skill 也要做回归测试:阿里开源 skill-up,开始补上智能体工程的质量短板
阿里开源「skill-up」,专为Agent Skill打造的评测与演进工具:支持声明式用例、跨引擎验证、多轮对话测试及回归分析,助力AI能力从“能运行”迈向“可交付”。关注公众号回复「资料」获取AI测试开发合集。
|
5月前
阿里云 Chat App 消息服务 LINE 通道能力上线:打通日泰台出海私域
阿里云Chat App消息服务新增LINE通道,支持文本、图片、音视频及富媒体模板消息,覆盖日、泰、台等高渗透市场。现接入享服务费限免,助力企业本地化触达与社群运营。
948 0
|
7月前
|
运维 Cloud Native 应用服务中间件
阿里云微服务引擎 MSE 及 API 网关 2026 年 4 月产品动态
阿里云微服务引擎 MSE 面向业界主流开源微服务项目, 提供注册配置中心和分布式协调(原生支持 Nacos/ZooKeeper/Eureka )、云原生网关(原生支持Higress/Nginx/Envoy,遵循Ingress标准)、微服务治理(原生支持 Spring Cloud/Dubbo/Sentinel,遵循 OpenSergo 服务治理规范)能力。API 网关 (API Gateway),提供 APl 托管服务,覆盖设计、开发、测试、发布、售卖、运维监测、安全管控、下线等 API 生命周期阶段。帮助您快速构建以 API 为核心的系统架构.满足新技术引入、系统集成、业务中台等诸多场景需要。
阿里云微服务引擎 MSE 及 API 网关 2026 年 4 月产品动态
|
云安全 人工智能 安全
马年专属平安签已上线,诚邀您参与「云上体检 开签纳福」互动活动!
阿里云「云上体检 开签纳福」活动:扫码抽马年平安签,获云上安全寄语;完成「2026云上安全健康体检」即领福气盲盒(100%中奖),分享签文截图还可抽AirPods 4等大奖!
1121 7
|
11月前
|
人工智能 JavaScript 前端开发
【教案生成平台】实战教程四:开发所见即所得的在线试卷编辑器
本试卷编辑器基于Vue实现,支持拖拽排序、动态题型组件渲染(单选/简答等),实时A4预览,并通过html2canvas+jsPDF导出高清PDF。数据模型清晰,扩展性强,真正实现所见即所得的高效出卷体验。
876 19