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

升级Spring Boot至2.1.2后MongoDB查询报UnsupportedOperationException

解决Spring Boot 2.1.2升级后CommentRepository查询抛出UnsupportedOperationException的问题

你遇到的这个问题,核心是Spring Boot升级到2.1.2后,Spring HATEOAS与Jackson、JAXB的兼容性冲突导致的——Comment继承的ResourceSupport类使用了JAXB注解,但该类的links属性没有直接的setter方法,JPA/Jackson在实例化实体时尝试设置这个属性就会抛出异常。下面给你几个针对性的解决方案:

1. 替换ResourceSupport为RepresentationModel(推荐方案)

Spring HATEOAS从1.0.x版本(对应Spring Boot 2.1+)开始,已经将ResourceSupport标记为过时,官方推荐用RepresentationModel替代它。这个新类的设计更适配新版本Spring生态,完全避开了旧类中JAXB注解带来的兼容性问题。

修改你的Comment实体类:

import org.springframework.hateoas.RepresentationModel;

@ApiModel(description = "Comment")
@Document(collection = "comment")
@JsonInclude(Include.NON_NULL)
@Relation(value = "comment", collectionRelation = "comments")
public class Comment extends RepresentationModel<Comment> implements Serializable, UserIdentifiable {
    private static final long serialVersionUID = 116036486931198760L;
    
    @Id
    @ApiModelProperty(readOnly = true)
    private String commentId;
    
    @NotEmpty
    @ApiModelProperty(required = true)
    private String sectionId;
    
    @NotEmpty
    @ApiModelProperty(required = true)
    private String commentableType;
    
    // 其他原有属性和方法保持不变
}

替换后既保留了HATEOAS的链接管理能力,又彻底解决了注解冲突问题。

2. 忽略ResourceSupport的links属性

如果暂时不想替换父类,可以通过Jackson注解让序列化/反序列化过程忽略ResourceSupport中的links属性,避免触发无setter的错误:

@JsonIgnoreProperties({"links"})
@ApiModel(description = "Comment")
@Document(collection = "comment")
@JsonInclude(Include.NON_NULL)
@Relation(value = "comment", collectionRelation = "comments")
public class Comment extends ResourceSupport implements Serializable, UserIdentifiable {
    // 原有代码不变
}

这个注解会告诉Jackson跳过links属性的处理,直接绕过异常触发点。

3. 补充JAXB依赖(Java 9+环境适用)

Spring Boot 2.1.x开始默认不再包含JAXB相关依赖(Java 9及以上版本移除了JAXB模块),而ResourceSupport类依赖JAXB注解,缺少依赖会导致Jackson无法解析这些注解,进而引发异常。

在pom.xml中添加JAXB依赖:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.2</version>
</dependency>

添加后Jackson就能正确处理JAXB注解,消除异常根源。

4. 全局配置Jackson忽略未知属性

这是一个快速临时的解决方案,在application.properties中添加配置:

spring.jackson.deserialization.ignore-unknown=true

该配置会让Jackson忽略所有无法识别的属性,包括links,但可能隐藏其他潜在的属性映射问题,建议优先使用前面的方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:10:05