BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News ModelMapper: An Object To Object Mapping Library

ModelMapper: An Object To Object Mapping Library

This item in japanese

Bookmarks

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)

ModelMapper is available in Maven Central. For more information see the user guide and Javadoc. The source code is on GitHub.

Rate this Article

Adoption
Style

BT