2017-07-18 46 views
0

我有一個使用modelmapper在實體和DTO對象之間轉換的spring應用程序。我在DTO中有一個表示實體中的ZonedDateTime對象的字符串。我在SpringAppConfiguration中編寫了以下代碼片段Modelmapper不執行轉換器轉換方法

@Bean 
public ModelMapper contactModelMapper() { 

    Converter<String, ZonedDateTime> toZonedDateTimeString = new AbstractConverter<String, ZonedDateTime>() { 
     @Override 
     public ZonedDateTime convert(String source) { 
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
      LocalDateTime datel = LocalDateTime.parse(source, formatter); 
      ZonedDateTime result = datel.atZone(ZoneId.systemDefault()); 
      return result; 
     } 
    }; 
    Converter<ZonedDateTime, String> toStringZonedDateTime = new AbstractConverter<ZonedDateTime, String>() { 
     @Override 
     public String convert(ZonedDateTime source) { 
      String result = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(source); 
      return result; 
     } 
    }; 

    PropertyMap<Contact, ContactDTO> contactDTOmap = new PropertyMap<Contact, ContactDTO>() { 
     @Override 
     protected void configure() { 
      map().setTenantId(source.getTenant().getTenantId()); 
      //if (source.getCreatedDateTime() != null) map().setCreatedDateTime(source.getCreatedDateTime()); 
      //when(Conditions.isNotNull()).map(source.getCreatedDateTime(), map().getCreatedDateTime()); 
     } 
    }; 

    /* this is for userDTO to BO.. */ 
    PropertyMap<ContactDTO, Contact> contactMap = new PropertyMap<ContactDTO, Contact>() { 
     @Override 
     protected void configure() { 
      map().getTenant().setTenantId(source.getTenantId()); 
     } 
    }; 
    ModelMapper contactModelMapper = new ModelMapper(); 
    contactModelMapper.addMappings(contactDTOmap); 
    contactModelMapper.addMappings(contactMap); 
    contactModelMapper.addConverter(toStringZonedDateTime); 
    contactModelMapper.addConverter(toZonedDateTimeString); 
    return contactModelMapper; 
} 

正如你所看到的那裏有2個轉換器。從DTO字符串更改爲實體中的ZonedDateTime對象的那個根本不會被執行。反之亦然的轉換正常執行。

我很感謝任何幫助,對此的任何建議。

感謝

+0

有什麼建議嗎?我應該提供的任何信息? – kavita

回答

0

我有很多的在線閱讀和試驗後,解決了錯誤。看來addConverter調用的順序很重要。在轉換器轉換爲實體到dto轉換之後,我已將轉換器添加到實體轉換中。只要訂單正確,代碼就開始工作。發佈這個,以便它可以幫助某人作爲modelmapper的文檔非常不連貫..