java dto 实例,如何通过ModelMapper将Java记录用作DTO?

I'm refactoring my code. I want to use java records instead of java class in my DTO. To convert DTO to Entity, I'm using ModelMapper (version 2.3.5). When I try to get info about user (call method co convert Entity to DTO) I get this error.

Failed to instantiate instance of destination xxx.UserDto. Ensure that xxx.UserDto has a non-private no-argument constructor.

This is my code.

public record UserDto(String firstName,

String lastName,

String email,

String imageUrl) {}

@RestController

public class UserController {

@Autowired

private UserRepository userRepository;

@Autowired

private ModelMapper modelMapper;

@GetMapping("/user/me")

@PreAuthorize("hasRole('USER')")

public UserDto getCurrentUser(@CurrentUser UserPrincipal userPrincipal) {

return convertToDto(userRepository.findById(userPrincipal.getId())

.orElseThrow(() -> new ResourceNotFoundException("User", "id", userPrincipal.getId())));

}

private UserDto convertToDto(User user) {

UserDto userDto = modelMapper.map(user, UserDto.class);

return userDto;

}

private User convertToEntity(UserDto userDto) throws Exception {

User post = modelMapper.map(userDto, User.class);

return post;

}

}

Edit: Updating to version 2.3.8 doesn't help!

解决方案

The fields of a record are final, so they must be set through the constructor. Many frameworks will cheat and use various tricks to modify final fields after the fact anyway, but these will not work on records. If you want to instantiate a record, you have to provide all the field values at construction time.

It may take a little time for frameworks to learn about records. The old model of "call a no-arg constructor, then set the fields" will not work for records. Some frameworks are already able to deal with this (e.g., "constructor injection"), while others are not yet there. But, we expect that frameworks will get there soon enough.

As the commenters said, you should encourage your framework provider to support them. It isn't hard.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值