Spring Boot+Hibernate中@Type注解JSON映射报错问题
解决Hibernate @Type注解type属性无法解析的问题
问题原因
出现Cannot resolve method 'type'错误,核心原因是Spring Boot 3.x默认依赖的Hibernate 6.x已移除@Type注解的type属性,改用value属性替代;同时你当前使用的hibernate-types-5是适配Hibernate 5.x的版本,和Spring Boot 3.x的Hibernate版本不兼容。
解决方案
1. 替换Hibernate Types依赖
将pom.xml中的hibernate-types-5替换为适配Hibernate 6的版本:
<dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-6</artifactId> <version>2.20.0</version> </dependency>
版本号可根据最新稳定版调整,确保与Spring Boot版本兼容。
2. 修改实体类的@Type注解
把原@Type(type = "json")改为@Type(value = "json"),同时修复实体类的其他小问题:
@Type(value = "json") @Column(name = "contact_numbers", columnDefinition = "json") private ArrayList<String> contactNumbers; // 添加泛型,避免类型不安全
3. 修正实体类的其他细节
- 修复拼写错误:
custoemrName改为customerName - 给
ArrayList指定泛型(如ArrayList<String>),提升代码类型安全性
修改后的完整实体类:
package com.csbodima.demo.entity; import com.vladmihalcea.hibernate.type.json.JsonType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import java.util.ArrayList; @Entity @Table(name = "customer") @TypeDefs({ @TypeDef(name = "json", typeClass = JsonType.class) }) public class Customer { @Id @Column(name = "customer_id", length = 50) private int customerId; @Column(name = "customer_name", length = 200, nullable = false) private String customerName; @Type(value = "json") @Column(name = "contact_numbers", columnDefinition = "json") private ArrayList<String> contactNumbers; }
额外说明
若你使用的是Spring Boot 2.x(依赖Hibernate 5.x),无需替换依赖,只需确认导入的是org.hibernate.annotations.Type包而非其他同名注解即可。但更建议升级到Spring Boot 3.x配合Hibernate 6的生态。
内容的提问来源于stack exchange,提问作者Ay3sh
相关产品推荐
相关产品推荐

