- MapStruct Tutorial
- MapStruct - Home
- MapStruct - Overview
- MapStruct - Environment Setup
- Mapping
- MapStruct - Basic Mapping
- MapStruct - Custom Mapping
- MapStruct - Mapping Multiple
- MapStruct - Mapping Nested Bean
- MapStruct - Mapping Direct Field
- MapStruct - Builder
- Data Type Conversions
- MapStruct - Implicit Type Conversion
- MapStruct - Using numberFormat
- MapStruct - Using dateFormat
- MapStruct - Using expression
- MapStruct - Using constant
- MapStruct - Using defaultValue
- MapStruct - Using defaultExpression
- Mapping Collections
- MapStruct - Mapping List
- MapStruct - Mapping Map
- Miscellaneous
- MapStruct - Mapping Streams
- MapStruct - Mapping Enum
- MapStruct - Throwing Exceptions
- MapStruct - Customizing Mapper
- MapStruct Useful Resources
- MapStruct - Quick Guide
- MapStruct - Useful Resources
- MapStruct - Discussion
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);