Montag, 10. März 2014

mapstruct - Java bean mappings

In the Java space there are a lot of tools for bean mappings, for example a common tool is Dozer. But the most tools I know, does a lot of magic, by using the Java reflection API, this is bad for debugging the bean mapping logic. Now there is a new and hot Java open source tool called  mapstruct. The project provides a simple way to map Java beans. By generating the mapping code from a Java interface with annotations. A simple mapping for a Car bean and a Engine bean  can be found in the code bellow.
Mapstruct also provides a simple way for own mappings, for this a mapper can be define by the uses attribute in the Mapper  annotation on the interface, the example use a mapper called PowerMapper. The implementation of this mapper  is shown in the code bellow.
How the generated bean mapper can be used is show in the following JUnit test.
More Details about mapstruct see the project documentation. I think mapstruct it is a very promising bean mapping tool, try it and leave some comments here.


  1. Nice post; Awesome to see MapStruct covered here! I think generating mappers at compile time really is the way to go. As you say it makes things so much easier to understand (and debug if required), and it provides a very fast feedback about incomplete or wrong mappings.

    Btw. if you just have one @Mapping annotation, you can omit the outer @Mappings annotation. Java 8 will make this even nicer, as it will allow to simply specify several @Mapping annotations on the same method.


    1. Thanks Gunnar for your comment and for the great bean mapping tool ;-)
      My opinion is, it is best if you need no bean mapping. But in real applications there are often situation you need it.

  2. Hi,nice post. Can you please help on how to generate the bean mapper implementation? i am using eclipse with maven and spring. Searched a lot, could not find a solution