- Getting Started
- Setting Up
- Mapping
- Source model
- Destination Model
- How It Works
- Handling Mismatches
- Conventional Configuration
- Validating Matches
- Next Steps
- Class ModelMap
- Nested Class Summary
- Nested classes/interfaces inherited from class java.util.AbstractMap
- Constructor Summary
- Method Summary
- Methods inherited from class java.util.LinkedHashMap
- Methods inherited from class java.util.HashMap
- Methods inherited from class java.util.AbstractMap
- Methods inherited from class java.lang.Object
- Methods inherited from interface java.util.Map
- Constructor Details
- ModelMap
- ModelMap
- ModelMap
- Method Details
- addAttribute
- addAttribute
- addAllAttributes
- addAllAttributes
- mergeAttributes
- Why Map?
- Why ModelMapper?
- Intelligent
- Refactoring Safe
- Convention Based
- Extensible
Getting Started
This section will guide you through the setup and basic usage of ModelMapper.
Setting Up
If you’re a Maven user just add the modelmapper library as a dependency:
org.modelmapper modelmapper 3.0.0
Otherwise you can download the latest ModelMapper jar and add it to your classpath.
Mapping
Let’s try mapping some objects. Consider the following source and destination object models:
Source model
// Assume getters and setters on each class class Order < Customer customer; Address billingAddress; >class Customer < Name name; >class Name < String firstName; String lastName; >class Address
Destination Model
// Assume getters and setters class OrderDTO
We can use ModelMapper to implicitly map an order instance to a new OrderDTO :
ModelMapper modelMapper = new ModelMapper(); OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class);
And we can test that properties are mapped as expected:
assertEquals(order.getCustomer().getName().getFirstName(), orderDTO.getCustomerFirstName()); assertEquals(order.getCustomer().getName().getLastName(), orderDTO.getCustomerLastName()); assertEquals(order.getBillingAddress().getStreet(), orderDTO.getBillingStreet()); assertEquals(order.getBillingAddress().getCity(), orderDTO.getBillingCity());
How It Works
When the map method is called, the source and destination types are analyzed to determine which properties implicitly match according to a matching strategy and other configuration. Data is then mapped according to these matches.
Even when the source and destination objects and their properties are different, as in the example above, ModelMapper will do its best to determine reasonable matches between properties according to the configured matching strategy.
Handling Mismatches
While ModelMapper will do its best to implicitly match source and destination properties for you, sometimes you may need to explicitly define mappings between properties.
ModelMapper supports a variety of mapping approaches, allowing you to use any mix of methods and field references. Let’s map Order.billingAddress.street to OrderDTO.billingStreet and map Order.billingAddress.city to OrderDTO.billingCity :
modelMapper.typeMap(Order.class, OrderDTO.class).addMappings(mapper -> < mapper.map(src ->src.getBillingAddress().getStreet(), Destination::setBillingStreet); mapper.map(src -> src.getBillingAddress().getCity(), Destination::setBillingCity); >);
PropertyMap orderMap = new PropertyMap() < protected void configure() < map().setBillingStreet(source.getBillingAddress().getStreet()); map(source.billingAddress.getCity(), destination.billingCity); >>); modelMapper.addMappings(orderMap);
Conventional Configuration
As an alternative to manually mapping Order.billingAddress.street to OrderDTO.billingStreet , we can configure different conventions to be used when ModelMapper attempts to match these properties. The Loose matching strategy, which more loosely matches property names, will work in this case:
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
Additional matching strategies and other conventions can also be configured to control ModelMapper’s property matching process.
Validating Matches
Aside from writing tests to verify that your objects are being mapped as expected, ModelMapper has built-in validation that will let you know if any destination properties are unmatched.
First we have to let ModelMapper know about the types we want to validate. We can do this by creating a TypeMap :
modelMapper.createTypeMap(Order.class, OrderDTO.class);
Or we can add mappings from a PropertyMap which will automatically create a TypeMap if one doesn’t already exist for the source and destination types:
modelMapper.addMappings(new OrderMap());
Then we can validate our mappings:
If any TypeMap contains a destination property that is unmatched to a source property a ValidationException will be thrown.
Next Steps
Congratulations! You’ve learned how to map objects with safety and ease.
There’s a lot more to ModelMapper, including the complete mapping API and configuration options. Check out the user manual to learn more. You can also check out some additional examples of ModelMapper in action.
Copyright 2011-2019 Jonathan Halterman and friends. Released under the Apache License v2.0.
Class ModelMap
Implementation of Map for use when building model data for use with UI tools. Supports chained calls and generation of model attribute names.
This class serves as generic model holder for Servlet MVC but is not tied to it. Check out the Model interface for an interface variant.
Nested Class Summary
Nested classes/interfaces inherited from class java.util.AbstractMap
Constructor Summary
Method Summary
Copy all attributes in the supplied Collection into this Map , using attribute name generation for each element.
Copy all attributes in the supplied Map into this Map , with existing objects of the same name taking precedence (i.e.
Methods inherited from class java.util.LinkedHashMap
Methods inherited from class java.util.HashMap
Methods inherited from class java.util.AbstractMap
Methods inherited from class java.lang.Object
Methods inherited from interface java.util.Map
Constructor Details
ModelMap
ModelMap
ModelMap
Construct a new ModelMap containing the supplied attribute. Uses attribute name generation to generate the key for the supplied model object.
Method Details
addAttribute
addAttribute
Add the supplied attribute to this Map using a generated name . Note: Empty Collections are not added to the model when using this method because we cannot correctly determine the true convention name. View code should check for null rather than for empty collections as is already done by JSTL tags.
addAllAttributes
Copy all attributes in the supplied Collection into this Map , using attribute name generation for each element.
addAllAttributes
mergeAttributes
Copy all attributes in the supplied Map into this Map , with existing objects of the same name taking precedence (i.e. not getting replaced).
Why Map?
Applications often consist of similar but different object models, where the data in two models may be similar but the structure and concerns of the models are different. Object mapping makes it easy to convert one model to another, allowing separate models to remain segregated.
Why ModelMapper?
The goal of ModelMapper is to make object mapping easy, by automatically determining how one object model maps to another, based on conventions, in the same way that a human would — while providing a simple, refactoring-safe API for handling specific use cases.
Intelligent
ModelMapper analyzes your object model to intelligently determine how data should be mapped. There’s no manual mapping needed. ModelMapper does most of the work for you, automatically projecting and flattening complex models.
Refactoring Safe
ModelMapper provides a simple, fluent mapping API for handling special use cases. The API is type-safe and refactoring-safe, using actual code, rather than string references, to map properties and values.
Convention Based
ModelMapper uses conventions to determine how properties and values are mapped to each other. Users can create custom conventions, or use one of the supplied conventions.
Extensible
ModelMapper supports integration with any type of data model. From JavaBeans and JSON trees to database records, ModelMapper does the heavy lifting for you.
YourKit is kindly supporting open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit’s leading software products: YourKit Java Profiler and YourKit .NET Profiler.
YourKit is kindly supporting Modelmapper open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit’s leading software products: YourKit Java Profiler and YourKit .NET Profiler.
Copyright 2011-2019 Jonathan Halterman and friends. Released under the Apache License v2.0.