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

Spring Data JPA插入NULL值时规避NullPointerException问题咨询

问题解决:空值时向SQL插入NULL避免空指针

问题根源

你的代码中,当profile.getTitle()返回null时,直接调用profile.getTitle().name()会触发空指针异常——因为null对象无法调用任何方法,而你错误地先执行了name()再用Optional包装,这时候空指针已经发生了。

解决方案

方案1:用Optional.ofNullable安全处理

先将profile.getTitle()用Optional.ofNullable包裹,再通过map调用name(),最后用orElse(null)返回null值:

profileRepository.create(
    profile.getId(),
    profile.getCustomerId(),
    Optional.ofNullable(profile.getTitle())
            .map(Title::name)
            .orElse(null),
    profile.getLocale()
);

这样如果profile.getTitle()为null,map操作会被跳过,直接返回null,不会触发空指针。

方案2:用三元运算符直接判断(更简洁)

直接通过null判断决定返回枚举name还是null:

profileRepository.create(
    profile.getId(),
    profile.getCustomerId(),
    profile.getTitle() != null ? profile.getTitle().name() : null,
    profile.getLocale()
);

方案3:让JPA自动处理枚举(更优雅)

修改Repository的方法参数类型为枚举Title,而非String,让Spring Data JPA自动处理枚举到字符串的转换,同时自动处理null值:

// 修改Repository的create方法
@Query(value = """
      INSERT INTO users(id, customerId, title, locale) VALUES (:id, :customerId, :title, :locale)
      """, nativeQuery = true)
void create(@Param("id") Long id,
            @Param("customerId") String customerId,
            @Param("title") Title title, // 这里改为Title类型
            @Param("locale") String locale);

调用时直接传递profile.getTitle()即可,无需手动调用name():

profileRepository.create(
    profile.getId(),
    profile.getCustomerId(),
    profile.getTitle(), // 直接传枚举对象,null时JPA自动插入NULL
    profile.getLocale()
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:34:56