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

Hibernate 6中JSON类型结合LocalDate存储异常求助(Spring 3.0)

解决Hibernate使用@JdbcTypeCode(SqlTypes.JSON)时Java 8时间类型序列化异常

问题分析

你在Spring 3.0中使用Hibernate的@JdbcTypeCode(SqlTypes.JSON)映射JSON字段时,遇到LocalDate类型序列化失败的问题,核心原因是Hibernate默认会自行创建Jackson ObjectMapper实例,不会自动复用Spring容器中你定义的@Primary ObjectMapper,导致你注册的JavaTimeModule和KotlinModule没有生效。

解决方案

方法一:通过HibernatePropertiesCustomizer绑定自定义ObjectMapper

创建一个HibernatePropertiesCustomizer Bean,将Spring容器中的自定义ObjectMapper注入到Hibernate的配置中,让Hibernate使用这个实例处理JSON序列化:

@Bean
fun hibernatePropertiesCustomizer(customObjectMapper: ObjectMapper): HibernatePropertiesCustomizer {
    return HibernatePropertiesCustomizer { hibernateProps ->
        hibernateProps["hibernate.type.jackson.object_mapper"] = customObjectMapper
    }
}

这个方法会直接让Hibernate复用你已经配置好的ObjectMapper,无需额外修改实体类注解。

方法二:指定JSON类型处理器并绑定ObjectMapper

如果方法一不生效,你可以显式指定Hibernate的JSON类型处理器,并将自定义ObjectMapper注入其中:

  1. 修改实体类的JSON字段注解,添加@Type指定JsonBinaryType:
import org.hibernate.type.JsonBinaryType

@JdbcTypeCode(SqlTypes.JSON)
@Type(JsonBinaryType::class)
var request: ReportRequestDto,
  1. 创建JsonBinaryType Bean,传入你的自定义ObjectMapper:
@Bean
fun jsonBinaryType(customObjectMapper: ObjectMapper): JsonBinaryType {
    return JsonBinaryType(customObjectMapper)
}

验证依赖

确保你的pom.xml中已经正确引入以下依赖(版本与Spring Boot 3.x匹配):

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
</dependency>

测试

重新启动应用后,尝试保存包含LocalDate属性的实体,异常应该会消失,LocalDate会被正确序列化为JSON格式的日期字符串(而非时间戳)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:20:23