How to map a DTO to an existing JPA entity?

后端 未结 4 1520
伪装坚强ぢ
伪装坚强ぢ 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:26

    You can define next class:

    public class ObjectMapperUtils {
    
        private static ModelMapper modelMapper = new ModelMapper();
    
        /**
         * Model mapper property setting are specified in the following block.
         * Default property matching strategy is set to Strict see {@link MatchingStrategies}
         * Custom mappings are added using {@link ModelMapper#addMappings(PropertyMap)}
         */
        static {
            modelMapper = new ModelMapper();
            modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        }
    
        /**
         * Hide from public usage.
         */
        private ObjectMapperUtils() {
        }
    
        /**
         * 

    Note: outClass object must have default constructor with no arguments

    * * @param type of result object. * @param type of source object to map from. * @param entity entity that needs to be mapped. * @param outClass class of result object. * @return new object of outClass type. */ public static D map(final T entity, Class outClass) { return modelMapper.map(entity, outClass); } /** *

    Note: outClass object must have default constructor with no arguments

    * * @param entityList list of entities that needs to be mapped * @param outCLass class of result list element * @param type of objects in result list * @param type of entity in entityList * @return list of mapped object with type. */ public static List mapAll(final Collection entityList, Class outCLass) { return entityList.stream() .map(entity -> map(entity, outCLass)) .collect(Collectors.toList()); } /** * Maps {@code source} to {@code destination}. * * @param source object to map from * @param destination object to map to */ public static D map(final S source, D destination) { modelMapper.map(source, destination); return destination; } }

    And use it for your needs:

    MyEntity entity = ObjectMapperUtils.map(dto, existingEntity);
    

提交回复
热议问题