BeanUtils.复制不工作-错误非空属性引用空值或瞬态值



我做了一个非常小的Spring启动应用程序,我正在练习如何使用BeanUtils.copy。我很奇怪,虽然我做的一切都很好,但错误仍然存在。

App工作正常如果我只使用实体表&通过@RequestBody &amp直接获取数据解析到存储库,但是当我尝试将数据从DTO表映射到UserEntity时,它给了我一个错误:

"not-null property references a null or transient value"

任何帮助都将不胜感激。

控制器

@PostMapping
public ResponseEntity<Object> createUser(@RequestBody UserDetailsRequestModel userDetails){
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(userEntity, userDetails);
userRepository.save(userEntity);
return ResponseEntity.ok("Created");
}

UserRespository

公共接口UserRepository扩展crudrepositoryuserentity <{}

公共类UserEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable=false)
private String userId;
@Column(nullable=false, length=50)
private String firstName;
@Column(nullable=false, length=50)
private String lastName;
@Column(nullable=false, length=120)
private String email;
@Column(nullable=false)
private String encryptedPassword;

}

public class UserDetailsRequestModel(DTO) {
private String userId;
private String firstName;
private String lastName;
private String email;
private String encryptedPassword;
}

我从PostMan发送的数据,

{
"userId": "12",
"firstName": "John",
"lastName": "Doe",
"email": "John@doe.com",
"encryptedPassword": "123"
}

错误是没有使用BeanUtils正确的方式。

BeanUtils.copyProperties(userEntity, userDetails);

正确的方法是:

BeanUtils.copyProperties(userDetails, userEntity);

实际上,要抛出数据的目的表应该放在第二位。

相关内容

最新更新