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

Spring Boot使用BeanUtils.copyProperties报非空属性引用空/瞬态值错误

错误根源

你调用org.springframework.beans.BeanUtils.copyProperties()时参数顺序传递错误,该方法的参数规则是第一个参数为源对象,第二个参数为目标对象。
你当前写的BeanUtils.copyProperties(userEntity, userDetails)是将刚初始化的空UserEntity对象的属性值,覆盖到从请求体解析得到的UserDetailsRequestModel对象上,最终要持久化的userEntity所有业务字段均为null,触发了实体类上@Column(nullable=false)的非空约束校验,因此抛出对应错误。

修复代码

调整Controller层copyProperties的参数顺序即可,修改后代码如下:

@PostMapping
public ResponseEntity<Object> createUser(@RequestBody UserDetailsRequestModel userDetails){
    UserEntity userEntity = new UserEntity();
    // 源为请求入参对象userDetails,目标为要持久化的实体对象userEntity
    BeanUtils.copyProperties(userDetails, userEntity);
    userRepository.save(userEntity);
    return ResponseEntity.ok("Created");
}

额外提示

  • 如果你导入的是org.apache.commons.beanutils.BeanUtils,它的copyProperties参数顺序和Spring版本正好相反(目标在前,源在后),不同工具类混用时要注意区分所属包,避免重复踩坑。
  • 你的UserEntity中id字段已经配置了自增策略,若不需要手动指定业务userId,后续可以去掉请求中的对应参数,避免和生成逻辑冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:06:05