Spring Boot 3整合Spring Data JPA操作PostgreSQL时API报错解决
问题解决:Spring Boot 3 + Spring Data JPA 操作PostgreSQL时的GET 500/POST 400异常
问题背景
用Spring Boot 3开发基础REST API,原本基于自定义ContentCollectionRepository的API运行正常,切换到Spring Data JPA操作PostgreSQL后出现异常:
- GET请求返回500内部服务器错误
- POST请求返回400错误请求
排查过程
- 移除实体类中的
desc字段后,GET请求恢复正常,确认该字段是触发500错误的核心原因 - 进一步排查POST请求的400错误,最终定位为枚举类型的序列化/反序列化不兼容问题
解决方法
针对两类问题分别修复:
- GET 500问题:
desc是SQL关键字,不能直接作为实体类字段名,需重命名字段并通过@Column映射到数据库对应列 - POST 400问题:确保枚举类支持前后端枚举值的序列化/反序列化兼容,比如处理大小写、指定存储策略
相关代码示例
修复前的问题代码
@Entity @Table(name = "content_collection") public class ContentCollection { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // 问题1:desc是SQL关键字,直接作为字段名触发SQL语法错误 // 问题2:枚举未配置序列化/反序列化规则 private CollectionType desc; // getter/setter } public enum CollectionType { ARTICLE, VIDEO, AUDIO }
修复后的正确代码
@Entity @Table(name = "content_collection") public class ContentCollection { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // 重命名字段,避免SQL关键字冲突,映射到数据库的collection_desc列 @Column(name = "collection_desc") // 指定枚举以字符串类型存储到数据库 @Enumerated(EnumType.STRING) private CollectionType collectionDesc; // getter/setter } // 枚举类添加JSON反序列化支持,兼容前端传入的大小写值 public enum CollectionType { ARTICLE, VIDEO, AUDIO; @JsonCreator public static CollectionType fromString(String value) { return CollectionType.valueOf(value.toUpperCase()); } }
Spring Data JPA Repository
public interface ContentCollectionRepository extends JpaRepository<ContentCollection, Long> { }
错误日志示例
GET请求500错误日志
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "desc" Position: 123
POST请求400错误日志
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `com.example.enums.CollectionType` from String "article": not one of the values accepted for Enum class: [ARTICLE, VIDEO, AUDIO]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.example.enums.CollectionType` from String "article": not one of the values accepted for Enum class: [ARTICLE, VIDEO, AUDIO]
内容的提问来源于stack exchange,提问作者Ehtesham
相关产品推荐
相关产品推荐

