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.




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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Graph Protocol — Indexer prospective

Adding Text Summarization with Sumy into Flask API with Chrome Extension on Frontend

How to Build a Successful Cloud Migration Strategy

Weekly Assignment 5

4 Effortless Steps for Contributing To Open Source Projects

Image of many people’s hands painted red to make a heart.

Stop writing extra code — you can do it in SQL instead

How to Create Local Git Branches


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

More from Medium

Never write Getters/Setters again! 😍

3 Essentials for long-running batch jobs

The Semantic Emptiness of Objects in the If Statement

S.O.L.I.D Principles