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

使用Spring Data JPA审计生成H2表时如何调整列顺序将时间字段移至末尾

解决方案

JPA规范未对表列的生成顺序做强制要求,Hibernate默认会优先加载父类定义的属性,再加载子类属性,因此你继承的DateAudit审计字段会出现在业务字段之前,可通过以下两种方案实现需求:

方案1:使用Hibernate列排序注解(适用Hibernate 5.2+)

Hibernate扩展的@Column注解提供order属性,数值越小列优先级越高、越靠前,你可以给审计字段设置较大的order值即可放到表末尾。

代码修改示例

  1. 修改DateAudit类字段注解:
package ru.omega.vaccination.model.dto.audit;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.Instant;

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(
    value = {"createdAt", "updatedAt"},
    allowGetters = true
)
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public abstract class DateAudit implements Serializable {

  @CreatedDate
  @Column(nullable = true, updatable = false)
  @org.hibernate.annotations.Column(order = 100)
  private Instant createdAt;

  @LastModifiedDate
  @Column(nullable = true)
  @org.hibernate.annotations.Column(order = 101)
  private Instant updatedAt;

}
  1. 给People类的业务字段设置较小的order值:
@Entity(name = "people")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class People extends DateAudit  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    @org.hibernate.annotations.Column(order = 1)
    private Long id;
    
    @Column
    @org.hibernate.annotations.Column(order = 2)
    private String lastname;
    
    @Column
    @org.hibernate.annotations.Column(order = 3)
    private String firstname;
    
    @Column
    @org.hibernate.annotations.Column(order = 4)
    private String patronymic;

    ...
}

方案2:自定义建表脚本(全版本通用)

如果不想依赖Hibernate私有特性,可直接关闭Hibernate自动建表,手动编写建表脚本指定列顺序,Spring Boot会自动执行脚本初始化数据库。

配置步骤

  1. 在resources目录下新建schema.sql文件,编写建表语句:
CREATE TABLE IF NOT EXISTS people (
    id BIGINT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    lastname VARCHAR(255),
    firstname VARCHAR(255),
    patronymic VARCHAR(255),
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);
  1. 修改项目配置文件(以application.yml为例):
spring:
  sql:
    init:
      mode: always
  jpa:
    hibernate:
      ddl-auto: none # 关闭Hibernate自动建表逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:39:03