You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新版Hibernate中如何注册列类型?解决Spring Boot3.1.4适配问题

解决Spring Boot 3.1.4+Hibernate中Long类型对应数据库int类型的校验问题

问题背景

升级到Spring Boot 3.1.4后,配套的Hibernate版本更新,启动时触发Schema校验错误:

Schema-validation: wrong column type encountered in column [order_num] in table [assets]; found [int (Types#INTEGER)], but expecting [bigint (Types#BIGINT)]

实体类字段为Long类型,但数据库对应列是int类型,需全局映射该类型对应关系,无需修改所有受影响实体的字段定义。

解决方案:自定义MySQL 8 Dialect

Hibernate 6+(Spring Boot 3.x配套版本)调整了Dialect的类型注册逻辑,需通过registerColumnTypes方法结合TypeContributions完成类型映射:

1. 实现自定义Dialect

import org.hibernate.dialect.MySQL8Dialect;
import org.hibernate.type.SqlTypes;
import org.hibernate.type.descriptor.sql.IntegerSqlTypeDescriptor;
import org.hibernate.type.TypeContributions;
import org.hibernate.service.ServiceRegistry;

public class CustomMySQL8Dialect extends MySQL8Dialect {
    @Override
    public void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
        super.registerColumnTypes(typeContributions, serviceRegistry);
        // 将Hibernate对应Java Long的BIGINT类型,映射为数据库的int类型
        typeContributions.contributeSqlTypeDescriptor(SqlTypes.BIGINT, IntegerSqlTypeDescriptor.INSTANCE);
    }
}

2. 配置Spring Boot启用自定义Dialect

在application.properties中添加配置:

spring.jpa.properties.hibernate.dialect=com.yourpackage.CustomMySQL8Dialect

若使用application.yml则配置为:

spring:
  jpa:
    properties:
      hibernate:
        dialect: com.yourpackage.CustomMySQL8Dialect

补充方案:单个字段局部调整

如果仅少数字段需要适配,可直接在实体字段上指定列定义:

@Column(name = "order_num", columnDefinition = "int")
private Long orderNum;

注意事项

Java Long的取值范围远大于数据库int(int范围:-2^31 ~ 2^31-1),需确保业务中不会存入超出int范围的数据,否则会触发数据溢出异常。

内容的提问来源于stack exchange,提问作者Mejmo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 01:51:20