Home > OS >  map inherited DTO to Entity
map inherited DTO to Entity

Time:11-26

I have RestController that accept inheritance DTO:

@JsonSubTypes({
        @JsonSubTypes.Type(value = RealTimeEventDTO.class, name = "real-time"),
        @JsonSubTypes.Type(value = ScheduledEventDTO.class, name = "scheduled")
})
public class EventDTO {

    private Long id;

}

@Data
@NoArgsConstructor
public class RealTimeEventDTO extends EventDTO {

    private EventTriggerDTO eventTrigger;

    @Builder
    public RealTimeEventDTO(Long id, EventTriggerDTO eventTrigger) {
        super(id);
        this.eventTrigger = eventTrigger;
    }
}

I have same structure in Domain. And I need map DTO to Entity.

 private Event toEvent(EventDTO event) {
        return null;
    }

How Can I map inherited DTO to Entity?

CodePudding user response:

Take a look at Mapstruct, it's useful to map entities and dto properly

Event.java

public class Event {
    private Long id;
    private String content;

   // constructor, getters, setters, toString etc.
}

EventDTO.java

public class EventDTO {
    private Long id;
    private String payload;

   // constructor, getters, setters, toString etc.
}

IEventMapper.java

@Mapper
public interface IEventMapper {

    IEventMapper INSTANCE = Mappers.getMapper(IEventMapper.class);

    @Mapping(source = "payload", target = "content")
    public Event eventDTOToEvent(EventDTO eventDTO);
}

pom.xml

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.4.2.Final</version>
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.4.2.Final</version>
</dependency>

Usage

public class App {
    public static void main(String[] args) {

        EventDTO eventDTO = new EventDTO(123L, "Hello World !");

        Event event = IEventMapper.INSTANCE.eventDTOToEvent(eventDTO);

        System.out.println(event);
        System.out.println(eventDTO);

    }
}

Result

Event {id=123, content='Hello World !'}
EventDTO {id=123, payload='Hello World !'}
  • Related