SpringBoot基于注解的数据库字段回填方案

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

具体代码

数据库表

yaml 复制代码
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

plain 复制代码
<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

注解类

plain 复制代码
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RelationField {

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

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

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

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

RelationFieldMapping

数据转换

yaml 复制代码
@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.computeIfAbsent(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);
        }

    }

}

基础的一些代码

yaml 复制代码
@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
yaml 复制代码
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

plain 复制代码
@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

yaml 复制代码
@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private 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);
        List<ProductDetailRes> productDetailResList = BeanUtil.copyToList(productEntityList, ProductDetailRes.class);
        relationFieldMapping.map(productDetailResList);
        return productDetailResList;
    }

}

ProductController

yaml 复制代码
@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)
相关推荐
optimistic_chen2 小时前
【Java EE进阶 --- SpringBoot】Spring 核心 --- AOP
spring boot·笔记·spring·java-ee·aop·java注解
asom222 小时前
互联网大厂Java求职面试实战:Spring Boot到Kubernetes的技术问答
java·spring boot·kubernetes·oauth2·电商·microservices·面试技巧
虎子_layor3 小时前
轻量级哈希扰动工具:Hashids,快速上手
java·spring
烽学长3 小时前
(附源码)基于Spring boot的校园志愿服务管理系统的设计与实现
java·spring boot·后端
失散133 小时前
分布式专题——49 SpringBoot整合ElasticSearch8.x实战
java·spring boot·分布式·elasticsearch·架构
chinesegf4 小时前
[特殊字符] 常用 Maven 命令
java·spring boot·maven
杰克尼4 小时前
Springcloud_day01
spring boot·spring·mybatis
鸽鸽程序猿4 小时前
【项目】【抽奖系统】活动创建
java·spring
李慕婉学姐5 小时前
【开题答辩过程】以《割草机器人工作管理系统的设计与开发》为例,不会开题答辩的可以进来看看
java·spring·机器人