Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map different Java-Bean structures onto one another

In our project we have to map one nested structures of beans onto another. (These are actually JAXB mapped Java-Representations of XML documents that, say, represent an incoming order document.) This has to be mapped onto the quite different order document structure of another system.

What are the options to do this? I would prefer something that fulfills the following requirements:

  1. The mapping should alert me when the mapping of one field was not defined
  2. The mapping should have some defaults, like mapping fields of equal names onto one another and providing standard mappings for, say, int to String and vice versa.
  3. The mapping should be bidirectional.
  4. One should be able to use code completion when defining the mapping.

A promising framework for this is Dozer, but it does not fulfill 1 and 4. Same with JBeanMapper. Just programming it in Java does 4 but not the other requirements; using XSLT fulfills perhaps 2 but nothing else. Do you have better ideas?

like image 806
Hans-Peter Störr Avatar asked Dec 17 '08 11:12

Hans-Peter Störr


2 Answers

ModelMapper is the one library that meets all of your criteria. It offers a mapping API that uses actual code to map properties - so you get code completion. And it offers validation to ensure that all destination properties are mapped. Additionally it offers some things you didn't even know you wanted such as intelligent mapping :)

Check out the ModelMapper homepage for more info:

http://modelmapper.org

like image 92
Jonathan Avatar answered Oct 03 '22 19:10

Jonathan


Another alternative is MapStruct which generates mapping code at build time, resulting in type-safe mappings which don't require any dependencies at runtime (Disclaimer: I'm the author of MapStruct).

like image 34
Gunnar Avatar answered Oct 03 '22 17:10

Gunnar