Github Project - Version 0.12
Mailing list - Issues
Created & Maintained by Séven Le Mesle

Java bean mapping that compiles

Clone, map and transform beans like manual without pain

Rock solid

Mapping is checked at compilation, it is refactoring proof and debuggable

Lightening fast

Uses no reflection, no runtime processing, works as fast as manual mapping

Configuration as code

Uses only annotations to describe and configure mapping, no external configuration files

Annotation processor

Built with JSR 269, supports any Java version from v6, works anywhere (IDE, Maven, Gradle, ...)

Stupid Simple

Lightweight API, easy to learn, gives rich compiler message with tips for fix

Customizable

Supports custom mappers, mapping post-processor, custom field to field mapping

 

Getting started

Add Selma to your build

Selma is available in maven central, feel free to add it to your pom dependencies.

<!-- scope provided because the processor is only needed at compile time-->
<dependency>
    <groupId>fr.xebia.extras</groupId>
    <artifactId>selma-processor</artifactId>
    <version>0.12</version>
    <scope>provided</scope>
</dependency>

<!-- This is the only real dependency you will have in your binaries -->
<dependency>
    <groupId>fr.xebia.extras</groupId>
    <artifactId>selma</artifactId>
    <version>0.12</version>
</dependency>

Declare the mapper

Selma uses a mapper interface to describe and configure the needed mapping. Here we want to map Order to OrderDto and reverse.

@Mapper(
    withCustomFields = {
        @Field({"customer.fullName", "customerFullName"}),
        @Field({"reference", "ref"})
    },
    withIgnoredFields = "id"
)
public interface SelmaMapper {

    // This will build a fresh new OrderDto
    OrderDto asOrderDto(Order in);

     // This will update the given order
    Order asOrder(OrderDto in, Order out);

}

Here we defined some configuration for fields:

  1. Field fullName from the Customer class should be mapped to the field customerFullName in OrderDto
  2. Field reference from any class should be mapped to the field ref in any matching class
  3. Field id should be skipped because it does not exist in OrderDto

Use the mapper

Once built the generated mapper can be retrieved via Selma class.

// Get SelmaMapper
SelmaMapper mapper = Selma.builder(SelmaMapper.class).build();

// Map my InBean
OrderDto res = mapper.asOrderDto(in);

Build and enjoy

Compiler will report any issues like not mappable properties, unused mapping configuration or API miss-use.
Check out our sample app project.


 

News

Brand new release 0.11

This release adds Spring support using the new withIoc=SPRING. It is also now possible to use a Selma mapper as the custom mapper of another one.

See release notes or Milestone 0.11.

Brand new release 0.10

This release deprecates @IgnoreFields and @Fields. The new @Maps annotation should now be used instead. It supports all the parameters available in @Mapper at the method scope.

  • #35: Deploy snapshots to sonatype snapshot repository
  • #36: Deprecate @IgnoreFields and @Fields in favor of a new annotation
  • #37: Add support for update graph in custom mappers
  • #38: Add support for scoped custom mappers
  • #40: Add compilation error when default enum value does not exist
  • #41: Compilation error when fields have no getter
  • #42: Support scoped mapping interceptor
  • #43: Remove deprecated @IgnoreFields from warning messages
  • #44: Add support for qualified class name in custom fields mapping
  • #45: Add support for custom embedded field to root level field
  • #46: Add support for ignore missing fields in source bean, destination bean or both
  • #47: Fix missing custom mapper in type mapping registry

See release notes or Milestone 0.10.


 

Documentation

Mapping beans properties

Selma match properties using setter and getter names. Selma can map only same field names. By default, properties not existing in both source and destination beans will break compilation.

Same propertie names

Duplicate Beans

You can use Selma to build duplicates of your beans or map from model to DTO when they shares same property names.

Model Bean
public class Person {

    private String firstName;
    private String lastName;
    private Date birthDay;
    private int age;
    private Long[] indices;
    private Collection tags;

    // + Getters and Setters
}
Mapper interface
@Mapper
public interface PersonMapper {

    // Returns a duplicate of the source Person
    Person duplicatePerson(Person source);
}

Mapping to DTO

Selma can reduce a model bean to a DTO containing a sublist of the properties.

DTO Bean
public class PersonDTO {

    private String firstName;
    private String lastName;
    private Date birthDay;

    // + Getters and Setters
}
Mapper interface
@Mapper(withIgnoreMissing = IgnoreMissing.DESTINATION)
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);
}

Here we used IgnoreMissing.DESTINATION to indicate we wish to ignore properties (age, indices, tags) from source bean missing in destination bean. But we could also choose to specify each ignored fields.

Mapper listing ignored fields
@Mapper(withIgnoreFields = {"age", "Person.indices", "fr.xebia.selma.Person.tags"})
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);
}

Here we used prefixes Person and fr.xebia.selma.Person to show that you can match ignored fields using simple class name or FQCN prefix.

Mapping from DTO

Selma can use a reduced DTO to build a model bean.

Mapper interface
@Mapper(withIgnoreMissing = IgnoreMissing.SOURCE)
public interface PersonMapper {

    // Returns a new instance of Person mapped from PersonDTO source
    Person asPerson(PersonDTO source);
}

Here we used IgnoreMissing.SOURCE to indicate we wish to ignore properties (age, indices, tags) missing in source bean.

Mapping to and from DTO

A mapper interface can describe multiple mapping methods.

Mapper interface
@Mapper
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    @Map(withIgnoreMissing = IgnoreMissing.DESTINATION)
    PersonDto asPersonDTO(Person source);

    // Returns a new instance of Person mapped from PersonDTO source
    @Map(withIgnoreMissing = IgnoreMissing.SOURCE)
    Person asPerson(PersonDTO source);
}

Here we used @Map annotation to describe mapping per method. Please notice that @Mapper configuration is available for all mapping methods while @Map is only applied to a single method. Both annotations provides the exact same parameters.

Disabling missing field checks

By default Selma checks every single missing properties but you can choose to disable these helpfull checks.

Mapper ignoring all missing properties
@Mapper(withIgnoreMissing = IgnoreMissing.ALL)
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);

    // Returns a new instance of Person mapped from PersonDTO source
    Person asPerson(PersonDTO source);
}

Here we used IgnoreMissing.ALL to disable missing properties checking. So we removed @Map annotation, feel free to combine @Mapper and @Map in the same mapper.

@Map configuration inherits and override @Mapper configuration.

Mapping nested beans

Selma takes care of generating mapping for the complete bean graph. Each embedded bean will be mapped in it's own method of the generated code. You can customize the mapping

Person Bean
public class Person {

    private String firstName;
    private String lastName;
    private Date birthDay;
    private Address residency;

    // + Getters and Setters
}
Address Bean
public class Address {

    private String line1;
    private String line2;
    private String zipCode;
    private String city;
    private String country;

    // + Getters and Setters
}
Mapper declaring nested bean
@Mapper
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);

    // Returns a new instance of AddressDTO mapped from Address source
    @Map(withIgnoreFields = "country")
    AddressDTO asAddress(Address source);
}

Here we declared the asAddress(Address source) method in the mapper interface to demonstrate we can do it. asPersonDTO(Person source) implementation will call asAddress(Address source). Note that you do not need to declare this method for the mapping to work.

@Map annotation can be used to configure the mapping of each nested bean in the graph.

Customize property names mapping

You can define custom property to property mapping using withCustomFields parameter available in @Mapper and @Map.

Person Bean
public class Person {

    private String firstName;
    private String lastName;
    private Date birthDay;

    // + Getters and Setters
}
PersonDTO Bean
public class PersonDTO {

    private String name;
    private String lastName;
    private Date birthDate;

    // + Getters and Setters
}
Mapper with custom property names
@Mapper(
    withCustomFields = {
        @Field({"firstName","name"}), @Field({"Person.birthDay","birthDate"})
    }
)
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);

    // Returns a new instance of Person mapped from PersonDTO source
    Person asPerson(PersonDTO source);
}

This configuration will map firstName to name property and birthDay to birthDate property. The @Field annotation define a route that will be applied from PersonDTO to Person and reverse.

@Field supports prefixes to match fields names using simple class name or FQCN prefix. You can also define custom fields in @Map annotation.

Flatten bean mapping

You can flatten properties from nested bean using withCustomFields parameter available in @Mapper and @Map.

Person Bean
public class Person {

    private String firstName;
    private String lastName;
    private Date birthDay;

    // See Address bean (line1, line2, zipCode, city, country)
    private Address address;

    // + Getters and Setters
}
PersonDTO Bean
public class PersonDTO {

    private String firstName;
    private String lastName;
    private Date birthDay;
    private String addressLine1;
    private String addressLine2;
    private String addressZipCode;
    private String addressCity;
    private String addressCountry;

    // + Getters and Setters
}
Mapper flattening properties from nested bean
@Mapper(
    withCustomFields = {
        @Field({"address.line1","addressLine1"}), @Field({"address.line2","addressLine2"}),
        @Field({"address.zipCode","addressZipCode"}), @Field({"address.city","addressCity"}),
        @Field({"address.country","addressCountry"})
    }
)
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);

    // Returns a new instance of Person mapped from PersonDTO source
    Person asPerson(PersonDTO source);
}

This configuration will flatten properties from Address bean to address* properties in PersonDTO. It also works to unflatten the properties from PersonDTO to Person and Address.

@Field may flatten from any level of the graph. You are not limited to first nested bean but can point a property from any nesting level.

Updating destination bean

Instead of creating a new instance of the destination bean, you can choose to map the source bean against a given instance of the destination bean. You only need to declare a second parameter in your mapping methods that will be used as destination instance.

Mapper updating a destination bean
@Mapper
public interface PersonMapper {

    // Returns the given destination PersonDto mapped from Person source
    PersonDto updatePersonDTOFromPerson(Person source, PersonDto destination);

    // Returns the given destination Person mapped from PersonDTO source
    Person updatePersonFromPersonDTO(PersonDTO source, Person destination);
}

Mapping enums

Selma can map enums using a same value strategy by default. Selma will generate a new method for every single enum to enum mapping required, using a switch block without default.

Person Bean
public class Person {

    private String firstName;
    private String lastName;
    private Date birthDay;
    private PersonKind kind;

    public enum PersonKind {
       SIMPLE_CUSTOMER, PRODUCER, BUSINESS_CUSTOMER
    }
    // + Getters and Setters
}
PersonDTO Bean
public class PersonDTO {

  private String firstName;
    private String lastName;
    private Date birthDay;
    private PersonKindDto kind;

    public enum PersonKindDto {
       SIMPLE_CUSTOMER, PRODUCER, BUSINESS_CUSTOMER
    }
    // + Getters and Setters
}
Mapper mapping same enum values
@Mapper
public interface PersonMapper {

    // Returns a new instance of PersonDTO mapped from Person source
    PersonDto asPersonDTO(Person source);

}
Generated mapping method
/**
   * Mapping method overridden by Selma
   */
  public final PersonKindDto asSalesChannelDto(PersonKind in) {
    fr.xebia.extras.selma.beans.PersonKindDto out = null;
    if (in != null) {
      switch (in) {
        case SIMPLE_CUSTOMER :  {
          out = fr.xebia.extras.selma.beans.PersonKindDto.SIMPLE_CUSTOMER;
          break;
        }
        case PRODUCER :  {
          out = fr.xebia.extras.selma.beans.PersonKindDto.PRODUCER;
          break;
        }
        case BUSINESS_CUSTOMER :  {
          out = fr.xebia.extras.selma.beans.PersonKindDto.BUSINESS_CUSTOMER;
          break;
        }
      }
    }
    return out;
  }

Selma will raise compilation errors when both enums does not contain the same values.

Enums with default value

Selma can map enums using a same value strategy with a default value. The default value will be used for values not existing in both enums.

Person Bean
public class PersonDto {

    private String firstName;
    private String lastName;
    private Date birthDay;
    private PersonKindDto kind;

    public enum PersonKindDto {
       CUSTOMER, PRODUCER
    }
    // + Getters and Setters
}
Default value
@Mapper
public interface PersonMapper {

    // Map SIMPLE_CUSTOMER and BUSINESS_CUSTOMER to CUSTOMER
    @Map(
         withEnums = @EnumMapper(from=PersonKind.class, to=PersonKindDto.class, defaultValue="CUSTOMER")
    )
    PersonDto asPersonDTO(Person source);

    // Map SIMPLE_CUSTOMER and BUSINESS_CUSTOMER to CUSTOMER
    @EnumMapper(defaultValue="CUSTOMER")
    PersonKindDto asPersonKindDto(PersonKind source);

}

Here we demonstrated 2 ways of declaring a default value for your enum mapping:

  1. First one, declares a @Map with enum, so we need to declare both from and to enum with a default value.
  2. Second one, declares a @EnumMapper directly on a method mapping two enums types, with a default value.

It is also possible to declare the enumMapper inside @Mapper.
With this configuration SIMPLE_CUSTOMER and BUSINESS_CUSTOMER will be mapped to CUSTOMER.

To have more control over the enum mapping, you will need to declare a custom mapper.

Mapping with custom mapper

Sometimes, Selma will not do what you need. Let say, you want to convert from String to date or from Integer to Float. In Selma, we do not want magic conversion, so converting from boxed Integer to native int and reverse is supported but, we do not support auto-magically convert from int to float because there can be data loss. So you can define your own custom mapper.
A custom mapper is a class that contains one or more methods taking an input parameter (the source bean / value) and return the destination value after hand coded mapping. You only need to add the class to the withCustom attribute of the @Mapper or @Map annotation.

Person Bean
public class Person {

    private String name;
    private Address address;

    // + Getters and Setters
}
PersonDTO Bean
public class PersonDTO {

    private String name;
    private String address;

    // + Getters and Setters
}
Custom mapper mapping address to string
public class AddressCustomMapper {

    // Returns a string representation of the address
    public String addressAsString(Address source){

        return source.toString();
    }

}
Mapper declaring a custom mapper
@Mapper(withCustom = AddressCustomMapper.class)
public class PersonMapper {

    // Returns a PersonDTO instance mapped from source
    PersonDTO asPersonDTO(Person source);

}

The PersonMapper generated class will use the AddressCustomMapper addressAsString method to map the Address to String.

Update destination bean

You can use custom mappers to update the destination bean as described in updating destination bean. For this kind of use the custom mapping method should declare a second parameter giving the destination bean.

Custom mapper updating destination
public class AddressCustomMapper {

    // Update des CustomMapper
    public Address carFromDto(String addressString, Address destination) {
        String [] lines = addressString.split('\n');
        if (lines.length > 0){
            dest.setFirstLine(lines[0]);
        }
        if (lines.length > 1){
            dest.setSecondLine(lines[1]);
        }
        return dest;
    }

}

All custom mapper class should define a public default constructor so the generated class can instantiate it. Just remember, for selma, method name is nothing, just ensure to define the good In/Out type pair.
Unused custom mapper will be reported as a compilation warning.

Mapping interceptor

Not convinced by custom mapper, you need to do special things on the source or target bean after the mapping occurs. Selma, allows you to define a hook in the custom mapper which will be executed after the mapping itself. You just need to define a method returning void and taking two parameters the source bean and the destination bean. See the example below:

public class AddressCustomMapper {

    public void interceptAddressToDto(Address source, AddressDto destination) {
        // Do some processing here the destination is already mapped.
    }

}

interceptAddressToDto will be called by the generated mapping code at the end of the mapping process.

Every custom mapper instance can be injected in the generated class when you build it from Selma. This allows custom mappers to use some services of your application code.

Mapping immutable types

By default Selma tries to map every bean. This means that given the same source and destination propertie types, Selma will generate code to build a fresh new instance for the destination field.
If you want to directly use the source field in destination passing source reference to the destination field, you should tell Selma that this is an immutable type.

Person Bean
public class Person {

    private String name;
    private String phoneNumber;
    private Date birthDate;
    private Address address;

    // + Getters and Setters
}
PersonDTO Bean
public class PersonDTO {

    private String name;
    private String phoneNumber;
    private Address address;

    // + Getters and Setters
}
Mapper passing by reference
@Mapper(withImmutables = Address.class)
public class PersonMapper {

    // Returns a PersonDTO instance mapped from source with same address
    @Map(withIgnoreMissing = IgnoreMissing.DESTINATION)
    PersonDTO asPersonDTO(Person source);

}

This mapper will pass by reference any mapping from Address to Address. You can specify as many immutables type as you want. It is also possible to declare immutables inside @Map.

Using factory

Some beans can not be built with a default empty constructor. For some reason the application code use a factory to provide new instances of these beans. Default Selma behavior is to call a default constructor without parameters.
To solve this issue without using reflection at runtime, Selma supports sourced beans, the idea is to pass one or more parameters to the constructor call in the generated code.

Person Bean bound to a DataSource
public class Person {

    private final DataSource ds;
    private String name;
    private String phoneNumber;
    private Date birthDate;

    // Constructor with DataSource
    public Person (DataSource ds){
        this.ds = ds;
    }

    // + Getters and Setters
}
PersonDTO Bean
public class PersonDTO {

    private String name;
    private String phoneNumbe;
    private Date birthDate;

    // + Getters and Setters
}
Mapper declaring a source
@Mapper(withSources = DataSource.class)
public class PersonMapper {

    // Returns a Person instance mapped from source populated with a DataSource
    Person asPerson(PersonDTO source);

}

This mapper will pass the given DataSource instance to the Person constructor. To see how to inject the DataSource instance refer to Building the mapper.

Future releases will support factory methods and factory class, so you can choose to use reflection on youre own.

Building the mapper

Now that you've define the mapping contract you need, you probably want to retrieve the generated mapper instance. All you need to know for this is the Selma class. It provides a builder API to build and configure your mapper instance.

Builder API
PersonMapper mapper = Selma.builder(PersonMapper.class).
                        withCustom(customMappers).
                        withSource(dataSources).
                        disableCache().build();

Here we build a PersonMapper, providing to it custom mappers and sources.

  1. We start a builder for the PersonMapper mapper interface.
  2. We use withCustom(...) to provide our custom mappers.
  3. We use withSource(...) to provide sources to our sourced beans.
  4. We call disableCache() to bypass mapper instance cache and force Selma to build a new mapper instance .

By default Selma maintains a cache of the previously loaded mappers, so mappers instance are considered Singleton.

Configuration

Selma can be used from Java 6 to 8.

Using Maven

Old releases of the maven compiler plugin tend to badly support annotation processor messages. We use successfully version 3.2.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.2</version>
    <configuration>
        <showWarnings>true</showWarnings>
        <optimize>true</optimize>
        <showDeprecation>true</showDeprecation>
    </configuration>
</plugin>

You can also use the annotation processor maven plugin if you can not move to maven compiler 3.2.

<plugin>
    <groupId>org.bsc.maven</groupId>
    <artifactId>maven-processor-plugin</artifactId>
    <version>2.2.4</version>
    <configuration>
        <defaultOutputDirectory>
            ${project.build.directory}/generated-sources
        </defaultOutputDirectory>
        <processors>
            <processor>fr.xebia.extras.selma.codegen.MapperProcessor</processor>
        </processors>
    </configuration>
    <executions>
        <execution>
            <id>process</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>process</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>fr.xebia.extras</groupId>
            <artifactId>selma-processor</artifactId>
            <version>${selma.version}</version>
        </dependency>
    </dependencies>
</plugin>

You can find help about configuring eclipse here.

Snapshot builds

You can retrieve snapshots builds from 0.12-SNAPSHOT in the sonatype snapshot repository. For this to work, you should add Sonatype snaphot repository in your maven settings.xml or pom.xml

<repositories>
    <repository>
        <id>oss-sonatype</id>
        <name>oss-sonatype</name>
        <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>