In this tutorial, you will learn using MapStruct for mapping/converting Java objects, JPA/Hibernate entity to DTO and vice versa. Let's get started to build a RESTful APIs example with Spring Boot and MySQL to see how MapStruct playing in the context.

What you'll need

  • Docker CE 18+

Project structure

Setting up MapStruct

MapStruct is a Java annotation processor for generating bean mapping classes.

To set up, add MapStruct dependency into pom.xml and configure annotationProcessorPaths of maven-compiler-plugin. Full project dependencies and build plugins as below


Define JPA/Hibernate Entity, DTO, Repository, and Service



DTO, stands for Data Transfer Object, is a design pattern used for customizing/aggregating data input and output so reducing the number of call to remote API.



Define MapStruct Mapper

To using MapStruct, you have to define a @Mapper interface which declares any required mapping methods to map between entity and DTO


Here you only define simple method signatures, converting Entity to DTO, DTO to Entity, List of Entity to List of DTOs. MapStruct will generate implementation code for you during build time.

Using MapStruct on REST API

Inject your previous defined @Mapper interface into REST API and start using its methods.


Wow! what a clean REST API without writing a single mapping/converting logic :)

Application Configuration



Run the application

Prepare Dockerfile for Java/Spring Boot application


Start your application and infrastructure via Docker Compose. Make sure your local Docker is running and your bash console is at the springboot-examples project root directory.

docker-compose -f docker-compose-restful.yaml up --renew-anon-volumes springboot-mapstruct

Test with curl

Create a new product

curl -i -H "Content-Type: application/json" -X POST -d '{"name":"Hello Koding","description": "Simple coding examples and tutorials","price":"1"}' http://localhost:8080/api/v1/products

Find all products

curl -i http://localhost:8080/api/v1/products

That's it! Thanks for joining and have a happy coding. You can find the full source code as below

Source code

https://github.com/hellokoding/springboot-examples/tree/master/restful-api/springboot-mapstruct