How to map a DTO to an existing JPA entity?

后端 未结 4 1433
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 10:49

I\'m trying to map a Java DTO object to an existing JPA entity object without having to do something like the following:

public MyEntity mapToMyEntity(SomeDT         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 11:34

    Translated from Portuguese

    https://pt.stackoverflow.com/questions/166438/dto-assembler-como-utiliza-lo-realmente

    Use Pattern Assembler: You could convert Entity to DTO through the assembler pattern but it is wrong (I think), it breaks the sense of the DTO which is a standard for transferring objects. See that it can be composed by of several entities. The correct thing is to use set methods of the instances of the objects in the classes of services, taking the DTO's and assembling them as entities, it is simply because you are working correctly with the standard.

    But it has a way that even if it being wrong it would work, but only a 1 x 1 association between entity x DTO, use Guava function.

    Eg: to convert Translate to transform into objects and lists with

    import java.util.ArrayList;
    import java.util.List;
    import com.google.common.base.Function;
    
        /**
         * Classe de transformação para popular os dados em DTOs, seguindo o pattern
         * Transfer Object Assembler.
         */
        public class Transformer {
    
            /**
             * Executa a transformação de um objeto para um DTO.
             * 
             * @param from
             * @param function
             * @return  T
             */
            public static  T transform(F from, Function function) {
                return (from == null) ? null : function.apply(from);
            }
    
            /**
             * Executa a transformação de uma lista de objetos para uma lista de DTOs.
             * 
             * @param fromList
             * @param function
             * @return  List
             */
            public static  List transform(List source, Function function) {
                List out = new ArrayList<>(source.size());
    
                for (F from : source) {
                    out.add(function.apply(from));
                }    
                return out;
            }    
        }
    

    Pattern assembler:

    import java.util.List;
    import br.com.myapp.model.dto.AuthUserDTO;
    import br.com.myapp.model.entity.AuthUser;
    import com.google.common.base.Function;
    import com.google.common.collect.Lists;
    
    /**
     * Classe que transforma entidade USUARIOS em DTO.
     * 
     * @author Dilnei Cunha
     */
    public class AuthUserDTOAssembler implements Function{
    
        /**
         * Método responsável por fazer a conversão da entidade USUARIOS em um AuthUserDTO.
         */
    @Override
    public AuthUserDTO apply(AuthUser e) {
    
        AuthGroupDTO groupDTO = Transformer.transform(e.getAuthGroup(), new  AuthGroupDTOAssembler());
    
        return new AuthUserDTO(e.getId(),
                           e.getName(),
                           e.getPassword(),
                           e.getEmail(),
                           e.getCreationDate(),
                           e.getLastModificationdate(),
                           e.getLastAccessDate(),
                           e.getAtivo(),
                           e.getUserName(),
                           e.getRamal(),
                           groupDTO);
        }
    }
    

    What would be the service that would use these patterns ...

    /**
     * Método responsável por buscar um AuthUserDTO pelo ID do usuário.
     */
    @Override
    public AuthUserDTO findById(Long id) {
        return Transformer.transform(authUserRepository.findUserById(id), new AuthUserDTOAssembler());
    }
    

    Now let's do the inverse process of turning one or a list of DTOs into objects, but keep in mind that the association was 1x1. To do this, simply reverse the objects in the implementation of the function, eg:

    import java.util.List;
    import br.com.myapp.model.dto.AuthUserDTO;
    import br.com.myapp.model.entity.AuthUser;
    import com.google.common.base.Function;
    import com.google.common.collect.Lists;
    
    /**
     * @author Dilnei Cunha
     */
    public class AuthUserAssembler implements Function{
    
    @Override
    public AuthUser apply(AuthUserDTO e) {
    
            AuthGroup group = Transformer.transform(e.getAuthGroupDTO(), new  AuthGroupAssembler());
    
            return new AuthUser(e.getId(),
                               e.getName(),
                               e.getPassword(),
                               e.getEmail(),
                               e.getCreationDate(),
                               e.getLastModificationdate(),
                               e.getLastAccessDate(),
                               e.getAtivo(),
                               e.getUserName(),
                               e.getRamal(),
                               group);
            }
        }
    

提交回复
热议问题