解决SpringDataJpa框架实体类表字段创建顺序与数据库表字段展示顺序不一致的问题

当使用SpringDataJpa和Hibernate时,发现数据库表字段顺序与实体类定义的顺序不一致,原因是Hibernate的PropertyContainer类使用TreeMap自动排序字段。为了解决这个问题,可以在项目中创建一个org.hibernate.cfg包,并重写PropertyContainer类,将TreeMap替换为LinkedHashMap以保持字段定义顺序。参考链接提供了详细解决方案。
摘要由CSDN通过智能技术生成

yml配置:

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  jpa:
    show-sql: false
    hibernate:
      ddl-auto: update

实体类代码:

@Getter
@Setter
@Entity
@Table(name = "t_db_bo_report")
public class UnreturnedFaultyBoReport extends BaseEntity {
    private static final long serialVersionUID = 1L;

    private String rmaLine;
    private String odaName;
    private String faultyChasing;
    private String yearMonthValue;
    private String remarks;


}

运行后发现数据库生成的字段顺序与实体类顺序不一致

原因:在org.hibernate.cfg包下的PropertyContainer类在取fields的时候是使用TreeMap来保存的,导致程序给字段自动排序了

解决方法:在项目中新建一个org.hibernate.cfg包名,重写PropertyContainer类(主要将treeMap改成linkedHashMap)

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.hibernate.cfg;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import javax.persistence.Access;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import org.hibernate.AnnotationException;
import org.hibernate.annotations.Any;
import org.hibernate.annotations.ManyToAny;
import org.hibernate.annotations.Target;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.boot.MappingException;
import org.hibernate.boot.jaxb.Origin;
import org.hibernate.boot.jaxb.SourceType;
import org.hibernate.cfg.annotations.HCANNHelper;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.jboss.logging.Logger;

class PropertyContainer {
    private static final CoreMessageLogger LOG = (CoreMessageLogger)Logger.getMessageLogger(CoreMessageLogger.class, PropertyContainer.class.getName());
    private final XClass xClass;
    private final XClass entityAtStake;
    private final AccessType classLevelAccessType;
    private final LinkedHashMap<String, XProperty> persistentAttributeMap;

    PropertyContainer(XClass clazz, 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值