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

如何在Java Spring的POST请求体中允许空值?

问题:允许POST请求提交部分字段的VideoGame对象

定义的VideoGame Record

public record VideoGame(
        @Positive
        Integer id,
        @NotEmpty
        String title,
        @NotEmpty
        String console,
        @NotEmpty
        String genre,
        String publisher,
        String developer,
        Double critic_score,
        Double other_sales,
        LocalDate release_date,
        LocalDate last_update
) { }

对应的VideoGame Repository

@Repository
public class VideoGameRepository {

    private final JdbcClient jdbcClient;

    public VideoGameRepository(JdbcClient jdbcClient) {
        this.jdbcClient = jdbcClient;
    }

    public void create(VideoGame videoGame) {
        var newVideoGame = jdbcClient.sql("INSERT INTO videogamesalestest (id, title, console, genre, publisher, developer, critic_score, release_date, last_update)" +
                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
                .param(List.of(videoGame.id(), videoGame.title(), videoGame.console(), videoGame.genre(), videoGame.publisher(), videoGame.developer(), videoGame.critic_score(), videoGame.release_date(), videoGame.last_update()))
                .update();

        Assert.state(newVideoGame == 1, "Failed to insert new videoGame");
    }
}

控制器代码

@RestController
@RequestMapping("/api/videogames")
public class VideoGameController {

    private final VideoGameRepository videoGameRepository;

    public VideoGameController(VideoGameRepository videoGameRepository) {
        this.videoGameRepository = videoGameRepository;
    }

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping("")
    void create(@RequestBody VideoGame videoGame) {
        videoGameRepository.create(videoGame);
    }
}

测试的请求体

{
  "id": 1,
  "title": "NewGame",
  "console": "Xbox",
  "genre": "Action",
  "publisher": "CBGAMES",
  "developer": "CBGAMES",
  "critic_score": 10.0,
  "release_date": "2025-01-07",
  "last_update": null
}

遇到的问题

希望客户端提交POST请求时可以包含或不包含VideoGame的全部字段,尝试在请求体中设置字段为null时,收到500内部服务器错误。尝试给record字段添加@Nullable注解后,Repository中出现参数可能为null的警告。纠结是否需要将record改为类,或者有没有更符合Spring风格的实现方式,也考虑过用Optional,但知道这不是它的适用场景,同时不想强制客户端提交完整的record。

解决方案

核心问题是让请求体中的空值或缺失值能正常反序列化为VideoGame对象,解决方法是移除params()调用中的List.of()——因为List.of()遇到null元素会抛出NullPointerException,直接传递参数即可。无需给record字段添加@Nullable,也不需要在控制器中添加@Valid注解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:48:16