ModelMapper: An Object To Object Mapping Library
ModelMapper, is an object-to-object framework that converts Java Beans (Pojos) from one representation to another. It automates different object mappings with a "convention follows configuration" approach allowing at the same time advanced functionality for cases with special needs. It is similar (but not a direct port) to the AutoMapper library for .NET.
ModelMapper can map a Java object on another with much more compact code and zero configuration in the simpler cases. It supports:
- Name based mapping of object properties
- Copying of public, protected and private fields
- Skipping certain fields
- Converters that affect mapping (e.g. converting strings to lowercase)
- Mapping between fields of different types (e.g. from a string to a number)
- Mapping using conditions
- Loose mapping strategy when the default is not enough
- Validation of the mapping process so that all fields are accounted for
- Complete custom control of the mapping process for special cases
- Integration with Guice or Spring
Transforming objects from one representation to another is a common pattern in Enterprise applications. An example would be domain objects that are loaded from the database and must be shown to the user in the GUI. An object in its original database format will contain a lot of properties for its lifecycle, while the user might only be interested in one or two fields at each screen. So several times the Pojo used in the database (the JPA entity) is a bit different from the Pojo used in the GUI. This is the problem that ModelMapper attempts to solve. In general object transformations are observed when information changes layers inside an Enterprise application.
Other scenarios that involve object transformations are:
- Aggregating multiple objects into one
- Computing some additional metadata on an existing object
- Transforming objects for sending to external systems
- Filling default values on undefined properties
- Converting the existing properties in some way (mapping an object to itself)
How does this compare with other alternatives?
Re: How does this compare with other alternatives?
Dozer requires XML configuration for this and BeanUtils only converts objects whose property names match exactly. For use cases that require specific mappings between properties, ModelMapper provides a mapping API that uses actual code rather than XML or String references, making the mappings refactoring safe and type-safe:
Interesting and useful
D dest = map();
ali akbar azizkhani
Anatole Tresch Mar 03, 2015