MapStruct for automated DTO to Entity mapping and vice versa

WeInspire Technologies
2 min readDec 22, 2021


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.



WeInspire Technologies

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