ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Spring Data JPA主动生成表时列顺序杂乱的解决办法(最新版)
[打印本页]
作者:
种地
时间:
2024-11-27 10:20
标题:
Spring Data JPA主动生成表时列顺序杂乱的解决办法(最新版)
最近把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 persistentAttributeMap变量没有了,但多了一个List 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技术交流群
,到场交流与讨论,更好的学习与进步!
欢迎关注我的公众号:程序猿DD。第一时间了解前沿行业消息、分享深度技术干货、获取优质学习资源
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4