You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将_aud表内容输出为JSON?Spring Data Envers适配方案

解决方法

因为Spring Data Envers返回的Revisions、Revision是框架封装的复杂对象,Jackson默认无法直接序列化,所以需要手动转换为符合你需求的简单DTO(数据传输对象),再返回JSON数组。

步骤1:创建匹配目标JSON格式的DTO类

先定义一个和你期望的JSON结构完全对应的DTO,字段名保持一致(或者用@JsonProperty指定):

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;

public class AuditRecordDTO {
    private Long id;
    private Long rev;
    private Integer revtype;
    
    @JsonProperty("created_date")
    private Date createdDate;
    
    @JsonProperty("modified_date")
    private Date modifiedDate;

    // 全参构造器
    public AuditRecordDTO(Long id, Long rev, Integer revtype, Date createdDate, Date modifiedDate) {
        this.id = id;
        this.rev = rev;
        this.revtype = revtype;
        this.createdDate = createdDate;
        this.modifiedDate = modifiedDate;
    }

    // 需自行补充无参构造器、getter和setter方法
}

步骤2:修改控制器的GET方法

在控制器中,先获取Revisions对象,然后遍历每个Revision,提取所需字段并映射到DTO,最后返回DTO列表:

import org.springframework.data.history.Revision;
import org.springframework.data.history.Revisions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AuditController {

    private final PersonRepository personRepository;

    // 构造注入仓库
    public AuditController(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @GetMapping("/audit/{id}")
    public List<AuditRecordDTO> getRevisions(@PathVariable("id") long id) {
        Revisions<Long, Person> revisions = personRepository.findRevisions(id);
        
        // 将Revisions转换为DTO列表
        return revisions.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    // 转换单个Revision到DTO的工具方法
    private AuditRecordDTO convertToDto(Revision<Long, Person> revision) {
        Person person = revision.getEntity();
        return new AuditRecordDTO(
                person.getId(),
                revision.getRevisionNumber(),
                revision.getRevisionType().ordinal(), // ADD=0, MOD=1, DEL=2
                person.getCreatedDate(),
                person.getModifiedDate()
        );
    }
}

补充说明

  • revision.getRevisionNumber()对应JSON里的rev字段,是审计版本号
  • revision.getRevisionType().ordinal()对应revtype,Envers的RevisionType枚举中,ADD对应0、MOD对应1、DEL对应2,和你的需求匹配
  • 确保Person实体类中存在id、createdDate、modifiedDate这些字段,并且有对应的getter方法

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:44:16