Map objects of two different classes using Orika such that one class have additional attributes and auto increment id.

There are multiple Mapping framework available in java to map two objects of different class.

  1. Dozer
    Dozer is a mapping framework that uses recursion to copy data from one object to another.
  2. Orika
    Orika is a bean to bean mapping framework that recursively copies data from one object to another.The main difference between orika and dozer is that Orika uses bytecode generation. This allows for generating faster mappers with minimal overhead.
  3. MapStruct
    MapStruct is a code generator that generates bean mapper classes automatically.
  4. ModelMapper
    ModelMapper is a framework that aims to simplify object mapping, by determining how objects map to each other based on conventions. It provides type-safe and refactoring-safe API.
  5. JMapper
    JMapper aims to provide an easy-to-use, high-performance mapping between Java Beans. The framework aims to apply the DRY principle using Annotations and relational mapping.

In below example we will map objects of two different classes using orika. Suppose there are two classes as follows :

public class Person{
private String name;
private int age;
// constructor and getter & setter methods
}

public class Student{
private long id;
private String studentName;
private int age;
private String country;
// constructor and getter and setter
}

Problem Statement -

Map a list of objects of class Person to class Student using orika mapper such that attribute student.id = auto-increment value, student.country = “india”.

Solution-

Include orika maven dependency into in your pom.xml file

<!-- https://mvnrepository.com/artifact/ma.glasnost.orika/orika-core -->
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>1.5.4</version>
</dependency>

Code:

final DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();AtomicLong counter = new AtomicLong(1);mapperFactory.classMap(person.class, Student.class)
.field("name", "studentName")
.customize(new CustomMapper<Person, Student>() {
@Override
public void mapAtoB(Person person, Student student, MappingContext context)
{
student.setId(counter.getAndIncrement());
student.setCountry("india");
}
})
.byDefault()
.register();

final MapperFacade mapperFacade = mapperFactory.getMapperFacade();

// converting list of person object to list of student object

List<Person> personList = getPersonList();
List<Student> studentList = new ArrayList<>();
perosnList.forEach(p -> studentList.add( mapperFacade.map(p,Student.class)) );

Bibliography:

https://www.baeldung.com/java-performance-mapping-frameworks
https://stackoverflow.com/questions/68678048/set-auto-increment-value-of-an-attribute-while-mapping-two-class-using-orika

System Administrator and Full stack web developer.