5.8 Spring 3 Object Mapping

There are scenarios, particularly in large message-oriented business applications, where object transformation is required. For example, consider a complex Web Service where there is a separation between the data exchange model and the internal domain model used to structure business logic. In cases like this, a general-purpose object-to-object mapping facility can be useful for automating the mapping between these disparate models. Spring 3 introduces such a facility built on the Spring Expression Language (SpEL). This facility is described in this section.

5.8.1 Mapper API

The API to implement object mapping logic is simple and strongly typed:

package org.springframework.mapping;
    
public interface Mapper<S, T> {

    T map(S source, T target);   
        
}

To create your own Mapper, simply implement the interface above. Parameterize S as the type you are mapping from, and T as the type you are mapping to. The source and target arguments provided to you should never be null. Your Mapper may throw any RuntimeException if mapping fails. Take care to ensure your Mapper implementation is thread-safe.

Consider the following hand-coded Mapper example:

public class PersonDtoPersonMapper implements Mapper<PersonDto, Person> {

    public Person map(PersonDto source, Person target) {
        String[] names = source.getName().split(" ");
        target.setFirstName(names[0]);
        target.setLastName(names[1]);
        return target;
    }
    
}

In this trivial example, the Mapper maps the PersonDto's name property to the Person's firstName and lastName properties. The fully mapped Person object is returned.

5.8.2 General Purpose Object Mapper Implementation

A general purpose object-to-object mapping system exists in the org.springframework.mapping.support package. Built on the Spring Expression Language (SpEL), this system is capable of mapping between a variety of object types, including JavaBeans, Arrays, Collections, and Maps. It can perform field-to-field, field-to-multi-field, multi-field-to-field, and conditional mappings. It also can carry out type conversion and recursive mapping, which are often required with rich object models.

5.8.2.1 Usage

To obtain a general purpose object Mapper with its default configuration, simply call MappingFactory.getDefaultMapper(). Then invoke the Mapper by calling its map(Object, Object) operation:

MappingFactory.defaultMapper().map(aSource, aTarget);
				

By default, the defaultMapper will map the fields on the source and target that have the same names. If the field types differ, the mapping system will attempt a type conversion using Spring 3's type conversion system. Nested bean properties are mapped recursively. Any mapping failures will trigger a MappingException to be thrown. If there are multiple failures, they will be collected and returned in the MappingException thrown to the caller.

To illustrate this default behavior, consider the following source object type:

public class CreateAccountDto {
    private String number;
    private String name;
    private AddressDto address;
       
    public static class AddressDto {
        private String street;
        private String zip;    
    }
}

And the following target object type:

public class Account {
    private Long number;
    private String name;
    private Address address;
    
    public static class Address {
        private String street;
        private String city
        private String state;
        private String zip;    
    }
}

Now mapped in the following service method:

public void createAccount(CreateAccountDto dto) {
    Account account = (Account) MapperFactory.getDefaultMapper().map(dto, new Account());
    // work with the mapped account instance
}

In this example, the number, name, and address properties are automatically mapped since they are present on both the source and target objects. The AccountDto's address property is a JavaBean, so its nested properties are also recursively mapped. Recursively, the street and zip properties are automatically mapped since they are both present on the nested AddressDto and Address objects. Nothing is mapped to the Address's city and state properties since these properties do not exist on the AddressDto source.

5.8.2.2 Registering Explicit Mappings

When default mapping rules are not sufficient, explicit mapping rules can be registered by obtaining a MapperBuilder and using it to construct a Mapper. Explicit mapping rules always override the default rule. The MapperBuilder provides a fluent API for registering object-to-object Mapping rules:

Mapper<PersonDto, Person> mapper =
    MappingFactory.mappingBuilder(PersonDto.class, Person.class)
        .addMapping(...)
        .addMapping(...)
        .getMapper();

				

5.8.2.3 Mapping between two fields with different names

Suppose you need to map AccountDto.name to Account.fullName. Since these two field names are not the same, the default auto-mapping rule would not apply. Handle a requirement like this by explicitly registering a mapping rule:

builder.addMapping("name", "fullName")
				

In the example above, the name field will be mapped to the fullName field when the mapper is executed. No default mapping will be performed for name since an explicit mapping rule has been configured for this field.

5.8.2.4 Mapping a single field to multiple fields

Suppose you need to map PersonDto.name to Person.firstName and Person.lastName. Handle a field-to-multi-field requirement like this by explicitly registering a mapping rule:

builder.addMapping("name", new Mapper<String, Person>() {
    public Person map(String name, Person person) {
        String[] names = name.split(" ");
        person.setFirstName(names[0]);
        person.setLastName(names[1]);
        return person;        
    }
});
				

In the example above, the first part of the name field will be mapped to the firstName field and the second part will be mapped to the lastName field. No default mapping will be performed for name since an explicit mapping rule has been configured for this field.

5.8.2.5 Mapping multiple fields to a single field

Suppose you need to map CreateAccountDto.activationDay and CreateAccountDto.activationTime to Account.activationDateTime. Handle a multi-field-to-field requirement like this by explicitly registering a mapping rule:

builder.addMapping(new String[] { "activationDay", "activationTime" }, new Mapper<CreateAccountDto, AccountDto>() {
    public Account map(CreateAccountDto dto, Account account) {
        DateTime dateTime = ISODateTimeFormat.dateTime().parseDateTime(
            dto.getActivationDay() + "T" + dto.getActivationTime());
        account.setActivationDateTime(dateTime);
        return account;
    }
});
				

In the example above, the activationDay and activationTime fields are mapped to the single activationDateTime field. No default mapping is performed for activationDay or activationTime since an explicit mapping rule has been configured for these fields.

5.8.2.6 Mapping conditionally

Suppose you need to map Map.countryCode to PhoneNumber.countryCode only if the source Map contains a international phone number. Handle conditional mapping requirements like this by explicitly registering a mapping rule:

builder.addConditionalMapping("countryCode", "international == 'true'");
				

In the example above, the countryCode field will only be mapped if the international field is 'true'. international == 'true' is a boolean expression that must evaluate to true for the mapping to be executed. No default mapping is performed for countryCode since an explicit mapping rule has been configured for this field.

5.8.2.7 Forcing Explicit Mappings

You can force that all mapping rules be explicitly defined by disabling the "auto mapping" feature:

builder.setAutoMappingEnabled(false);
				

5.8.2.8 Registering Custom Mapping Converters

Sometimes you need to apply field specific type conversion or data transformation logic when mapping a value. Do this by registering a converter with a Mapping:

builder.addMapping("name", "fullName").setConverter() { new Converter<String, String>() {
    public String convert(String value) {
        // do transformation
        // return transformed value
    }
});
				

5.8.2.9 Ignoring Fields

Sometimes you need to exclude a specific field on a source object from being mapped. Do this by marking one or more source fields as excluded:

builder.setExcludedFields("name");
				

5.8.2.10 Registering Custom Type Converters

You may also register custom Converters to convert values between mapped fields of different types:

builder.addConverter(new Converter<String, Date>() {
    public Date convert(String value) {
        // do conversion
        // return transformed value    
    }
});
				

The example Converter above will be invoked anytime a String field is mapped to a Date field.

5.8.2.11 Registering Custom Nested Mappers

When mapping between two object graphs, you may find you need to register explicit mapping rules for nested bean properties. Do this by adding a nested Mapper:

builder.addNestedMapper(new Mapper<AddressDto, Address>() {
    public Address map(AddressDto source, Address target) {
        // do target bean mapping here
        return target; 
    }
});
				

The example Mapper above will map nested AddressDto properties to nested Address properties. This particular nested Mapper is "hand-coded", but it could have easily been another Mapper instance built by a MapperBuilder.

5.8.3 Further Reading

Consult the JavaDocs of MapperFactory and MapperBuilder in the org.springframework.mapping.support package for more information on the available configuration options.

Dozer is another general-purpose object mapper available in the open source Java community. Check it out at dozer.sourceforge.net.