如何通过ModelMapper将Java记录用作DTO? [英] How can I use Java records as DTO with ModelMapper?

查看:358
本文介绍了如何通过ModelMapper将Java记录用作DTO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构代码.我想在DTO中使用Java记录而不是Java类.要将DTO转换为Entity,我正在使用ModelMapper(版本2.3.5).当我尝试获取有关用户的信息(调用方法将Entity转换为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.

这是我的代码.

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;
    }
}

编辑 :更新到版本2.3.8没有帮助!

推荐答案

记录的字段是最终字段,因此必须通过构造函数进行设置.无论如何,许多框架都会在事实发生后作弊并使用各种技巧来修改最终字段,但是这些对记录无效.如果要实例化一条记录,则必须在构造时提供所有字段值.

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.

这篇关于如何通过ModelMapper将Java记录用作DTO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆