How can I use Java records as DTO with ModelMapper?

后端 未结 2 1867
北海茫月
北海茫月 2021-01-16 12:00

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 inf

相关标签:
2条回答
  • 2021-01-16 12:22

    record is a preview feature in Java 14 so I would recommend you to not use it on production. Secondly, it doesn't mimic java bean.

    record doesn't have a default no arg constructor implicitly if there are fields. If you wrote a no arg constructor, you will have to delegate the call to all args constructor and since all the fields are final you can only set them once. So you are kind of stuck there. See JEP 359:

    It is not a goal to declare "war on boilerplate"; in particular, it is not a goal to address the problems of mutable classes using the JavaBean naming conventions.

    An alternative that works today would be to use Lombok. Example of UserDto using Lombok:

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    public class UserDto {
        private String firstName;
        private String lastName;
        private String email;
        private String imageUrl;
    }
    
    0 讨论(0)
  • 2021-01-16 12:24

    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)
提交回复
热议问题