Conversion of DTO to entity and vice-versa

前端 未结 6 1166

I am using Spring MVC architecture with JPA in my web application. Where to convert data transfer object (DTO) to JPA entity and vice-versa, manua

6条回答
  •  轮回少年
    2020-12-25 12:06

    I can recommend to use mapstruct library:

    
        org.mapstruct
        mapstruct-jdk8
        1.2.0.Final
    
    

    For example, if you have such an entity:

    public class Entity {
        private Integer status;
        private String someString;
        private Date startDate;
        private Date endDate;
    
        // SKIPPED
    

    And DTO:

    public class Dto {
        private Boolean status;
        private String someString;
        private Long startDate;
        private Long endDate;
    
        // SKIPPED
    

    Then the transformation can be done in the service layer by this way:

    @Service
    public class SomeServiceImpl implements SomeService {
    
        @Autowired
        SomeDao someDao;
    
        @Autowired
        SomeMapper someMapper;
    
    
        public Dto getSomething(SomeRequest request) throws SomeException {
            return someDao.getSomething(request.getSomeData())
                    .map(SomeMapper::mapEntityToDto)
                    .orElseThrow(() -> new SomeException("..."));
        }
    

    Mapper can be represented as follows:

    @Mapper 
    public interface SomeMapper {
        @Mappings(
                {@Mapping(target = "entity", 
                          expression = "java(entity.getStatus() == 1 ? Boolean.TRUE : Boolean.FALSE)"),
                 @Mapping(target = "endDate", source = "endDate"),
                 @Mapping(target = "startDate", source = "startDate")
                })
    
        Dto mapEntityToDto(Entity entity);
    }
    

提交回复
热议问题