Set auto increment value of an attribute while mapping two class using orika

577 views Asked by At
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
}

My requirement is to map list of objects of class Person to class Student using orika mapper such that attribute student.id = auto-increment value, student.country = "india".

My code is as follows:

final DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();

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(null); // HOW TO SET AUTO_INCREMENT ID ???
                    student.setCountry("india");
                 }
              })
             .byDefault()
             .register();

final MapperFacade mapperFacade = mapperFactory.getMapperFacade();

// converting list of perosn object to list of student object

 List<Person> personList = new ArrayList<>();
 personList = getPersonList();

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

queries: How to set id value autoincrement while mapping ? Any simpler and better solution except direct mapping?

1

There are 1 answers

0
Himanshu On

Define an atomic counter and use the method getAndIncrement() to increment its value.

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()); // YOUR SOLUTION
                    student.setCountry("india");
                 }
              })
             .byDefault()
             .register();