最近把Spring Boot的版本升级到了3.3.5,突然发现一个问题:当使用Spring Data JPA自动生成表的时候,所产生的列顺序与Entity类中的变量顺序不一致了。比如,有一个下面这样的Entity:

@Data
@Entity(name = "t_config")
@EntityListeners(AuditingEntityListener.class)
public class Config {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(length = 20)
    private String itemKey;
    @Column(length = 200)
    private String itemValue;
    @Column(length = 200)
    private String itemDesc;


    @CreatedDate
    private Date createTime;
    @LastModifiedDate
    private Date modifyTime;


}

实际自动创建出来的是这样的:

Spring Data JPA 自动生成表列顺序混乱问题,老方法已失效,查收最新版吧_新版本

自动创建的表结构中各个列与Entity类中的变量顺序不一致。其实该问题是一个老生常谈的问题了,在DD这次升级的工程里是有做过解决方案的。只是升级了Spring Boot版本之后,之前的解决方案失效了。

搜索了一番,同时还问了一下AI,发现给出的方案还都是老的解决方案,所以今天特别写一篇来记录下新版本之下,要如何解决这个问题。如果您刚好遇到类似的问题,可以参考本文来解决。

老版本解决方案

新老版本的解决思路是类似的,都是替换Hibernate的实现,下面是老版本的解决步骤:

  1. 1. 在工程中新建org.hibernate.cfg
  2. 2. 找到hibernate-core包下的org.hibernate.cfg下的PropertyContainer类,复制到本工程的org.hibernate.cfg包下
  3. 3. 把PropertyContainer类中定义的persistentAttributeMap类型从TreeMap修改为LinkedHashMap

新版本解决方案

虽然之前的方案失效了,但思路应该还是对的,所以第一反应是看看当前版本下的PropertyContainer类,具体如下(省略了一些不重要的内容):

package org.hibernate.boot.model.internal;


//省略...


public class PropertyContainer {


    private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, PropertyContainer.class.getName());


    /**
     * The class for which this container is created.
     */
    private final XClass xClass;
    private final XClass entityAtStake;


    /**
     * Holds the AccessType indicated for use at the class/container-level for cases where persistent attribute
     * did not specify.
     */
    private final AccessType classLevelAccessType;


    private final List<XProperty> persistentAttributes;


  //省略...


}

可以看到有两个重要变化部分:

  1. 1. PropertyContainer类的包名从org.hibernate.cfg改到了org.hibernate.boot.model.internal
  2. 2. 之前的TreeMap<String XProperty> persistentAttributeMap变量没有了,但多了一个List<XProperty> persistentAttributes。进一步观察这个新变量的处理过程,可以看到如下逻辑:

Spring Data JPA 自动生成表列顺序混乱问题,老方法已失效,查收最新版吧_hibernate_02

所以,新版的方案就以下两个步骤:

  1. 1. 在工程中新建org.hibernate.boot.model.internal
  2. 2. 找到hibernate-core包下的org.hibernate.boot.model.internal下的PropertyContainer类,复制到本工程的org.hibernate.boot.model.internal包下
  3. 3. 把PropertyContainer类中,上面图中红色圈出部门定义的localAttributeMap = new TreeMap<>();修改为localAttributeMap = new LinkedHashMap<>();