SpringBoot基于注解实现数据库字段回填的完整方案

2025-11-11 22:50

本文主要是介绍SpringBoot基于注解实现数据库字段回填的完整方案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解...

本文主要介绍一种便捷的数据库字段回填方案,比如存储的关联ID,但是需要查询出来名称,我们就不用再进行手动查询了,用注解自动查询数据库关联出来,下面的案例基于 SpringBoot + myBATis-plus + mysql

以下是完整的实现代码:

数据库表javascript

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `home_page` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `bom` (
  `id` int(11) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `size` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `product` (
  `id` int(11) NOT NULL,
  `code` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `bom_id` int(11) DEFAULT NULL,
  `user_code` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

pom.xml

<properties>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.39</version>
    </dependency>
</dependencies>

RelationField

注解类

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RelationField {

    /**
     * 数据源Mapper
     */
    Class<? extends BaseMapper<?>> source();

    /**
     * 关联条件字段(实体字段名)
     */
    String condition();

    /**
     * 关联条件值来源(函数式表达式)
     */
    String conditionValue();

    /**
     * 要映射的字段(实体字段名)
     */
    String target();
}

RelationFieldMapping

数据转换

@Slf4j
@Component
public class RelationFieldMapping {

    // 使用ConcurrentHashMap保证线程安全,缓存类级别的映射配置
    private static final Map<Class<?>, Map<MappingConfig, List<CacheTask>>> MAPPING_CONFIG_CACHE = new ConcurrentHashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 映射单个对象的关联字段
     */
    public void map(Object dto) {
        if (dto == null) {
            return;
        }

        try {
            Map<MappingConfig, List<MappingTask>> taskGroups = groupMappingTasks(dto);
            for (Map.Entry<MappingConfig, List<MappingTask>> entry : taskGroups.entrySet()) {
                executeBatchMapping(entry.getKey(), entry.getValue());
            }
  编程      } catch (Exception e) {
            log.error("映射对象关联字段失败: {}", dto.getClass().getSimpleName(), e);
        }
    }

    /**
     * 批量映射对象列表的关联字段
     */
    public <T> void map(List<T> dtos) {
        if (dtos == null || dtos.isEmpty()) {
            return;
        }

        try {
            if (dtos.size() == 1) {
                map(dtos.getFirst());
                return;
            }

            Map<MappingConfig, List<MappingTask>> taskGroups = groupCrossObjectTasks(dtos);
            for (Map.Entry<MappingConfig, List<MappingTask>> entry : taskGroups.entrySet()) {
                executeBatchMapping(entry.getKey(), entry.getValue());
            }
        } catch (Exception e) {
            log.error("批量映射关联字段失败", e);
        }
    }

    /**
     * 缓存类级别的映射配置(线程安全版本)
     */
    private Map<MappingConfig, List<CacheTask>> getCachedMappingConfigs(Class<?> clazz) {
        return MAPPING_CONFIG_CACHE.computeIfAbjavascriptsent(clazz, k -> {
            Field[] fields = clazz.getDeclaredFields();
            Map<MappingConfig, List<CacheTask>> configGroups = new HashMap<>();

            for (Field field : fields) {
                CacheTask cacheTask = createCacheTask(field);
                if (cacheTask != null) {
                    MappingConfig config = new MappingConfig(
                            cacheTask.mapperClass,
                            cacheTask.conditionField
                    );
                    configGroups.computeIfAbsent(config, k1 -> new ArrayList<>()).add(cacheTask);
                }
            }
            return configGroups;
        });
    }

    /**
     * 分组映射任务
     */
    private Map<MappingConfig, List<MappingTask>> groupMappingTasks(Object dto) {
        Map<MappingConfig, List<CacheTask>> cachedConfigs = getCachedMappingConfigs(dto.getClass());
        if (cachedConfigs.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<MappingConfig, List<MappingTask>> taskGroups = new HashMap<>();

        cachedConfigs.forEach((config, cacheTasks) -> {
            for (CacheTask cacheTask : cacheTasks) {
                MappingTask task = createMappingTask(dto, cacheTask);
                taskGroups.computeIfAbsent(config, k -> new ArrayList<>()).add(task);
            }
        });
        return taskGroups;
    }

    /**
     * 创建映射任务
     */
    private MappingTask createMappingTask(Object dto, CacheTask cacheTask) {
        // 直接从DTO中提取条件字段的值(注意:conditionValue是字段名,不是值)
        Object conditionValue = extractEntityField(dto, cacheTask.conditionValue);
        return new MappingTask(
                dto,
                cacheTask.targetField,
                cacheTask.mapperClass,
                cacheTask.conditionField,
                cacheTask.targetFieldName,
                conditionValue
        );
    }

    /**
     * 创建缓存任务
     */
    private CacheTask createCacheTask(Field targetField) {
        RelationField annotation = targetField.getAnnotation(RelationField.class);
        if (annotation == null) {
            return null;
        }
        return new CacheTask(
                targetField,
                annotation.source(),
                annotation.condition(),
                annotation.target(),
                annotation.conditionValue()
        );
    }

    /**
     * 分组跨对象映射任务
     */
    private <T> Map<MappingConfig, List<MappingTask>> groupCrossObjectTasks(List<T> dtos) {
        Map<MappingConfig, List<MappingTask>> taskGroups = new HashMap<>();

        for (T dto : dtos) {
            Map<MappingConfig, List<MappingTask>> dtoTasks = groupMappingTasks(dto);
            dtoTasks.forEach((config, tasks) -> taskGroups.computeIfAbsent(config, k -> new ArrayList<>()).addAll(tasks));
        }
        return taskGroups;
    }

    /**
     * 执行批量映射
     */
    private void executeBatchMapping(MappingConfig config, List<MappingTask> tasks) {
        if (tasks.isEmpty()) {
            return;
        }

        try {
            BaseMapper<Object> mapper = getMapper(config.mapperClass);
            Set<Object> distinctValues = extractDistinctValues(tasks);

            if (distinctValues.isEmpty()) {
                return;
            }

            // 获取所有需要查询的目标字段
            List<String> targetFields = tasks.stream()
                    .map(task -> task.targetFieldName)
                    .distinct()
                    .collect(Collectors.toList());

            Map<Object, Object> entityMap = queryEntities(mapper, config, distinctValues, targetFields);
            applyMappings(tasks, entityMap);

        } catch (Exception e) {
            log.error("执行批量映射失败: {}", config, e);
        }
    }

    /**
     * 获取Mapper实例
     */
    @SuppressWarnings("unchecked")
    private BaseMapper<Object> getMapper(Class<?> mapperClass) {
        try {
            return (BaseMapper<Object>) applicationContext.getBean(mapperClass);
        } catch (Exception e) {
            throw new RuntimeException("获取Mapper失败: " + mapperClass.getName(), e);
        }
    }

    /**
     * 提取去重值
     */
    private Set<Object> extractDistinctValues(List<MappingTask> tasks) {
        return tasks.stream()
                .map(task -> task.conditionValue)
                .collect(Collectors.toSet());
    }

    /**
     * 查询实体数据
     */
    private Map<Object, Object> queryEntities(BaseMapper<Object> mapper, MappingConfig config, Set<Object> values, List<String> targetFields) {
        try {
            QueryWrapper<Object> queryWrapper = buildQueryWrapper(config, values, targetFields);
            List<Object> entities = mapper.selectList(queryWrapper);

            Map<Object, Object> resultMap = buildResultMap(entities, config.conditionField);

            log.debug("查询完成: {} -> {}条记录 (目标字段: {})", config, resultMap.size(), targetFields);

            return resultMap;

        } catch (Exception e) {
            throw new RuntimeException("查询实体数据失败: " + config, e);
        }
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper<Object> buildQueryWrapper(MappingConfig config, Set<Object> values, List<String> targetFields) {
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();

        // 转换条件字段名为数据库字段名(驼峰转下划线)
        String dbConditionField = StrUtil.toUnderlineCase(config.conditionField);

        if (values.size() == 1) {
            queryWrapper.eq(dbConditionField, values.iterator().next());
        } else {
            queryWrapper.in(dbConditionField, values);
        }

        // 如果targetFields为空,则查询所有字段;否则查询指定字段
        if (targetFields.isEmpty()) {
            return queryWrapper;
        }

        // 查询所有需要的字段:条件字段 + 所有目标字段(转换为数据库字段名)
        String[] selectFields = new String[targetFields.size() + 1];
        selectFields[0] = dbConditionField;
        for (int i = 0; i < targetFields.size(); i++) {
            selectFields[i + 1] = StrUtil.toUnderlineCase(targetFields.get(i));
        }
        queryWrapper.select(selectFields);

        return queryWrapper;
    }

    /**
     * 构建结果映射
     */
    private Map<Object, Object> buildResultMap(List<Object> entities, String conditionField) {
        return entities.stream()
                .collect(Collectors.toMap(
                        entity -> extractEntityField(entity, conditionField),
                        Function.identity(),
                        (existing, replacement) -> existing // 处理重复key
                ));
    }

    /**
     * 应用映射结果
     */
    private void applyMappings(List<MappingTask> tasks, Map<Object, Object> entityMap) {
        for (MappingTask task : tasks) {
            try {
                Object entity = entityMap.get(task.conditionValue);
                if (entity != null) {
                    Object fieldValue = extractEntityField(entity, task.targetFieldName);
                    setFieldValue(task.dto, task.targetField, fieldValue);
                }
            } catch (Exception e) {
                log.warn("应用映射失败: {}.{}",
                        task.dto.getClass().getSimpleName(), task.targetField.getName(), e);
            }
        }
    }

    /**
     * 提取实体字段值
     */
    private Object extractEntityField(Object entity, String fieldName) {
        return ReflectUtil.getFieldValue(entity, StrUtil.toCamelCase(fieldName));
    }

    /**
     * 设置字段值
     */
    private void setFieldValue(Object obj, Field field, Object value) {
        ReflectUtil.setFieldValue(obj, field, value);
    }

    // 内部类定义
    private record MappingTask(Object dto, Field targetField, Class<? extends BaseMapper<?>> mapperClass,
                                   String conditionField, String targetFieldName, Object conditionValue) {
    }

    private record CacheTask(Field targetField, Class<? extends BaseMapper<?>> mapperClass,
                                 String conditionField, String targetFieldName, String conditionValue) {
    }

    private record MappingConfig(Class<? extends BaseMapper<?>> mapperClass, String conditionField) {

        @Override
        public String toString() {
            return String.format("MappingConfig[%s, condition=%s]",
                    mapperClass.getSimpleName(), conditionField);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            MappingConfig that = (MappingConfig) o;
            return Objects.equals(mapperClass, that.mapperClass) &&
                    Objects.equals(conditionField, that.conditionField);
        }

        @Override
        public int hashCode() {
            return Objects.hash(mapperClass, conditionField);
        }

    }

}

基础的一些代码

@Data
@TableName("bom")
public class BomEntity {

    private Long id;

    private String code;

    private String name;

    private String size;

}

@Data
@TableName("product")
public class ProductEntity {

    private Long id;

    private String code;

    private String name;

    private Long bomId;

    private String userCode;

}

@Data
@TableName("user")
public class UserEntity {

    private Long id;

    private String code;

    private String name;

    private String homePage;

}

@Repository
public interface BomMapper extends BaseMapper<BomEntity> {
}

@Repository
public interface ProductMapper extends BaseMapper<ProductEntity> {
}

@Repository
public interface UserMapper extends BaseMapper<UserEntity> {
}

application.yml

spring:
  datasource:
    url: jdbc:mysql://192.168.8.134:30635/test_1?useSSL=false
    username: super_admin
    password: super_admin
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

案例代码

ProductDetailRes

@Data
public class ProductDetailRes {

    private Long id;

    private String code;

    private String name;

    private Long bomId;

    @RelationField(source = BomMapper.class, condition = "id", conditionValue = "bomId", target = "name")
    private String bomName;

    @RelationField(source = BomMapper.class, condition = "id", conditionValue = "bomId", target = "size")
    private String bomSize;

    private String userCode;

    @RelationField(source = UserMapper.class, condition = "code", conditionValue = "userCode", target = "name")
    private String userName;

    @RelationField(source = UserMapper.class, condition = "code", conditionValue = "userCode", target = "homePage")
    private String userHomePage;

}

ProductService

@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    privjavascriptate RelationFieldMapping relationFieldMapping;

    public ProductDetailRes detail(Long id) {
        ProductEntity productEntity = productMapper.selectById(id);
        ProductDetailRes productDetailRes = BeanUtil.copyProperties(productEntity, ProductDetailRes.class);
        relationFieldMapping.map(productDetailRes);
        return productDetailRes;
    }

    public List<ProductDetailRes> list() {
        List<ProductEntity> productEntityList = productMapper.selectList(null);
        Lispythont<ProductDetailRes> productDetailResList = BeanUtil.copyToList(productEntityList, ProductDetailRes.class);
        relationFieldMapping.map(productDetailResList);
        return productDetailResList;
    }

}

ProductController

@RestController
@RequestMapping(value = "product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping(value = "detail")
    public ProductDetailRes detail(Long id) {
        return productService.detail(id);
    }

    @GetMapping(value = "list")
    public List<ProductDetailRes> list() {
        return productService.list();
    }

}

curl [http://localhost:8080/product/list](http://localhost:8080/product/list)

curl [http://localhost:8080/product/detail?id=1](http://localhost:8080/product/detail?id=1)

SpringBoot基于注解实现数据库字段回填的完整方案

到此这篇关于SpringBoot基于注解实现数据库字段回填的完整方案的文章就介绍到这了,更多相关SpringBoot数据库字段回填内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于SpringBoot基于注解实现数据库字段回填的完整方案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1156129

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三