MapStruct for automated DTO to Entity mapping and vice versa

This code example demonstrates the use of MapStruct when we need to convert basic objects into DTOs.

We start by adding the MapStruct dependencies to a Spring project. Here we use a new project, but the procedure is the same for mature projects as well.


For each entity we need a Mapper interface:

UtilizatorUtilizatorDTOMapper Interface@Mapper
public interface UtilizatorUtilizatorDTOMapper {
UtilizatorUtilizatorDTOMapper INSTANCE = Mappers.getMapper(UtilizatorUtilizatorDTOMapper.class);
UtilizatorDTO objToDto(Utilizator utilizator);
Utilizator dtoToObj(UtilizatorDTO destination);

Now we can build the entity and DTO:

Utilizator Entitypublic class Utilizator {
private String name;
private String address;
public Utilizator() {
public Utilizator(String name, String address) { = name;
this.address = address;
//getters & setters
UtilizatorDTOpublic class UtilizatorDTO {
private String name;
public UtilizatorDTO() {
public UtilizatorDTO(String name) { = name;
//getters & setters

For demonstration purposes we are going to use a Controller class to evaluate our Mapper.

Controller class@RestController
class Controller {
@GetMapping(value = "/mapstruct_simple_obj_to_dto.action")
public UtilizatorDTO mapstructSimpleObjToDto() {
Utilizator utilizator = new Utilizator("Gabi", "Krakovia 9A");
UtilizatorDTO utilizatorDTO = UtilizatorUtilizatorDTOMapper.INSTANCE.objToDto(utilizator);
return utilizatorDTO;

@GetMapping(value = "/mapstruct_simple_dto_to_obj.action")
public Utilizator mapstructSimpleDtoToObj() {
UtilizatorDTO utilizatorDTO = new UtilizatorDTO("Gabi");
Utilizator utilizator = UtilizatorUtilizatorDTOMapper.INSTANCE.dtoToObj(utilizatorDTO);
return utilizator;

Originally published at on October 08, 2019.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
WeInspire Technologies

WeInspire Technologies

Written by Gabriel Voicu — Senior Principal Lead Software Engineer @ Dell Technologies