Spring Data JPA自動生成表時列順序混亂的最新解決辦法
最近把Spring Boot的版本升級到了3.3.5,突然發(fā)現(xiàn)一個問題:當使用Spring Data JPA自動生成表的時候,所產(chǎn)生的列順序與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;
}實際自動創(chuàng)建出來的是這樣的:

自動創(chuàng)建的表結(jié)構中各個列與Entity類中的變量順序不一致。其實該問題是一個老生常談的問題了,在DD這次升級的工程里是有做過解決方案的。只是升級了Spring Boot版本之后,之前的解決方案失效了。
搜索了一番,同時還問了一下AI,發(fā)現(xiàn)給出的方案還都是老的解決方案,所以今天特別寫一篇來記錄下新版本之下,要如何解決這個問題。如果您剛好遇到類似的問題,可以參考本文來解決。
老版本解決方案
新老版本的解決思路是類似的,都是替換Hibernate的實現(xiàn),下面是老版本的解決步驟:
- 在工程中新建
org.hibernate.cfg包 - 找到
hibernate-core包下的org.hibernate.cfg下的PropertyContainer類,復制到本工程的org.hibernate.cfg包下 - 把
PropertyContainer類中定義的persistentAttributeMap類型從TreeMap修改為LinkedHashMap
新版本解決方案
雖然之前的方案失效了,但思路應該還是對的,所以第一反應是看看當前版本下的PropertyContainer類,具體如下(省略了一些不重要的內(nèi)容):
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<>();
到這里,在新版本中的這個問題就解決了。如果你也遇到了類似的問題,希望本文對你有所幫助。
到此這篇關于Spring Data JPA自動生成表時列順序混亂的解決辦法最新版的文章就介紹到這了,更多相關Spring Data JPA自動生成表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
mybatis3.3+struts2.3.24+mysql5.1.22開發(fā)環(huán)境搭建圖文教程
這篇文章主要為大家詳細介紹了mybatis3.3+struts2.3.24+mysql5.1.22開發(fā)環(huán)境搭建圖文教程,感興趣的小伙伴們可以參考一下2016-06-06
Java實現(xiàn)PDF文件添加文字圖片和圖片水印的實戰(zhàn)指南
在日常開發(fā)中,PDF 加水印是非常常見的需求,比如文件脫敏、版權標識等場景,本文將基于 iTextPDF 庫實現(xiàn) PDF 文件的文字水印和圖片水印添加,需要的朋友可以參考下2026-02-02

