MapStruct - Overview



MapStruct is an annotation processor which is plugged into Java Compiler. Once plugged in, it can be used by command line tools like maven, gradle to process the mapping annotation to create a mapper class at compile time.

When Mapping is required?

In multilayered applications, data objects are used to fetch data from database and UI interacts with Models. Now data fetched into data models is required to map to Model or java beans to be passed to UI.Consider the following case.

Entity class connected with database.

StudentEntity.java

@Entity
class StudentEntity {
   String id;
   String name;
}

Model class connected with UI.

Student.java

class Student {
   String id;
   String name;
}

How MapStruct Works?

MapStruct automates the process of creating a mapper to map data objects with model objects using annotations. It creates a mapper implementation at compile time which helps developer to figure out error during development and make is easy to understand. For example −

StudentMapper.java

@Mapper
class StudentMapper {
   StudentMapper INSTANCE = Mappers.getMapper( StudentMapper.class );   
   StudentEntity modelToEntity(Student student);
}

Now StudentMapper.INSTANCE can be used to get mapped objects easily.

StudentEntity studentEntity = StudentMapper.INSTANCE.modelToEntity(student);
Advertisements