DTO pattern: Best way to copy properties between two objects

后端 未结 6 1290
死守一世寂寞
死守一世寂寞 2020-12-12 12:33

In my application\'s architecture I usually send the object or list of objects from the data access layer to the web layer via the service layer, in which these objects get

6条回答
  •  时光说笑
    2020-12-12 13:29

    I suggest you should use one of the mappers' libraries: Mapstruct, ModelMapper, etc. With Mapstruct your mapper will look like:

    @Mapper
    public interface UserMapper {     
        UserMapper INSTANCE = Mappers.getMapper( UserMapper.class ); 
    
        UserDTO toDto(User user);
    }
    

    The real object with all getters and setters will be automatically generated from this interface. You can use it like:

    UserDTO userDTO = UserMapper.INSTANCE.toDto(user);
    

    You can also add some logic for your activeText filed using @AfterMapping annotation.

提交回复
热议问题