最近把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;
}
实际自动创建出来的是这样的:
自动创建的表结构中各个列与Entity类中的变量顺序不一致。其实该问题是一个老生常谈的问题了,在DD这次升级的工程里是有做过解决方案的。只是升级了Spring Boot版本之后,之前的解决方案失效了。
搜索了一番,同时还问了一下AI,发现给出的方案还都是老的解决方案,所以今天特别写一篇来记录下新版本之下,要如何解决这个问题。如果您刚好遇到类似的问题,可以参考本文来解决。
新老版本的解决思路是类似的,都是替换Hibernate的实现,下面是老版本的解决步骤:
org.hibernate.cfg
包hibernate-core
包下的org.hibernate.cfg
下的PropertyContainer
类,复制到本工程的org.hibernate.cfg
包下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;
//省略...
}
可以看到有两个重要变化部分:
PropertyContainer
类的包名从org.hibernate.cfg
改到了org.hibernate.boot.model.internal
TreeMap<String XProperty> persistentAttributeMap
变量没有了,但多了一个List<XProperty> persistentAttributes
。进一步观察这个新变量的处理过程,可以看到如下逻辑:所以,新版的方案就以下两个步骤:
org.hibernate.boot.model.internal
包hibernate-core
包下的org.hibernate.boot.model.internal
下的PropertyContainer
类,复制到本工程的org.hibernate.boot.model.internal
包下PropertyContainer
类中,上面图中红色圈出部门定义的localAttributeMap = new TreeMap<>();
修改为localAttributeMap = new LinkedHashMap<>();
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有