Mapstruct 简明教程
MapStruct - Overview
MapStruct 是一个插入 Java 编译器的注释处理器。一旦插入,就可以通过 maven、gradle 等命令行工具使用它来处理映射注释,并在编译时创建映射器类。
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?
在多层应用程序中,数据对象用于从数据库提取数据,而 UI 与模型交互。现在,需要将提取到数据模型中的数据映射到要传递给 UI 的模型或 Java bean 中。考虑以下情况。
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;
}
与 UI 相连的模型类。
Model class connected with UI.
Student.java
class Student {
String id;
String name;
}
How MapStruct Works?
MapStruct 自动化使用注释将数据对象与模型对象进行映射的映射器创建过程。它在编译时创建映射器实现,这有助于开发人员在开发期间找出错误并便于理解。比如 −
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);
}
现在,可以使用 StudentMapper.INSTANCE 轻松获取映射对象。
Now StudentMapper.INSTANCE can be used to get mapped objects easily.
StudentEntity studentEntity = StudentMapper.INSTANCE.modelToEntity(student);