当前位置:网站首页>An understanding of mapstruct domain transformation tool!
An understanding of mapstruct domain transformation tool!
2022-07-18 13:18:00 【qq_ one billion seven hundred and fifty-seven million five hund】
MapStruct Introduce :
In our daily development of hierarchical applications , In order to decouple the layers from each other , Generally, different objects are defined to transfer data between different layers , therefore , There are all kinds of XXXDTO、XXXVO、XXXBO And other objects derived from database objects , When transmitting data between different layers , Inevitably, these objects often need to be converted to each other .
At this time, there are generally two processing methods :① Use it directly Setter and Getter Method transformation 、② Use some tool classes for conversion (e.g. BeanUtil.copyProperties). In the first way, if there are many object attributes , There's a lot to write about Getter/Setter Code . Although the second way seems much simpler than the first way , But because it uses reflection , Performance is not very good , And there are many pitfalls in use . And the protagonist to be introduced today MapStruct Without affecting performance , At the same time, it solves the shortcomings of these two methods .
MapStruct What is it? :
MapStruct It's a code generator , It's based on Convention over configuration The method greatly simplifies Java bean Implementation of mapping between types . The automatically generated mapping transformation code uses only simple method calls , So fast 、 Type safe and easy to understand , Source warehouse Github Address MapStruct. in general , It has the following three characteristics :
1. Based on annotations
2. Automatically generate mapping transformation code at compile time
3. Type safety , High performance , Without relying on
1. introduce pom rely on :
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.1.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.1.Final</version>
<scope>compile</scope>
</dependency>Now there's a scene , Query one from the database user object ( contain id, user name , password , cell-phone number , mailbox , Roles these fields ) And a corresponding character object role( contain id, The role of , Role description these fields ), Now in controller Need to use user object id, User name and role name of role object Three attributes .
One way is to pass two objects directly controller layer , But there will be a lot of useless properties .
A more general way is to encapsulate the attributes that need to be used into One class (DTO), Data transfer is done by transferring instances of this class .
Test the first case :
User.java
@AllArgsConstructor
@Data
public class User {
private Long id;
private String username;
private String password;
private String phoneNum;
private String email;
private Role role;
} Role.java
@AllArgsConstructor
@Data
public class Role {
private Long id;
private String roleName;
private String description;
} UserRoleDto.java
@Data
public class UserRoleDto {
/**
* user id
*/
private Long userId;
/**
* user name
*/
private String name;
/**
* The role of
*/
private String roleName;
} MainTest.java
public class MainTest {
User user = null;
/**
* The simulation finds out from the database user object
*/
@Before
public void before() {
Role role = new Role(2L, "administrator", " Super administrator ");
user = new User(1L, "zhangsan", "12345", "17677778888", "[email protected]", role);
}
/**
* Analog handle user Object conversion to UserRoleDto object
*/
@Test
public void test1() {
UserRoleDto userRoleDto = new UserRoleDto();
userRoleDto.setUserId(user.getId());
userRoleDto.setName(user.getUsername());
userRoleDto.setRoleName(user.getRole().getRoleName());
System.out.println(userRoleDto);
}
} Use MapStruct Solve the above problems :
Here we use User.java、Role.java、UserRoleDto.java.
Create a new one UserRoleMapper.java, This is used to define User.java、Role.java and UserRoleDto.java Attribute correspondence rules between :
UserRoleMapper.java
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
/**
* @Mapper This is a definition of MapStruct Object property transformation interface , Specify conversion rules in this class
* At project build time , It will automatically generate implementation classes for interface modification , This implementation class copies the object property values
* componentModel Automatically generate converter implementation classes at compile time and put them into target In the folder
* nullValueCheckStrategy Can be omitted automatically null Assignment
* nullValueMappingStrategy The primitive returns the default bean, Not null null
*/
@Mapper(componentModel = "spring", nullValueCheckStrategy = ALWAYS,nullValueMappingStrategy = RETURN_DEFAULT)
public interface UserRoleMapper {
/**
* Gets an instance of an implementation class that is automatically generated by the class
* The properties in the interface are public static final Of Methods are public abstract Of
*/
UserRoleMapper INSTANCES = Mappers.getMapper(UserRoleMapper.class);
/**
* This method is used to implement the object property replication method
*
* @Mapping Used to define property replication rules source Specify source object properties target Specify target object properties
*
* @param user This parameter is the source object , That is, the object to be copied
* @return It returns the target object , Is the final result of the object
*/
@Mappings({
@Mapping(source = "id", target = "userId"),
@Mapping(source = "username", target = "name"),
@Mapping(source = "role.roleName", target = "roleName")
})
UserRoleDto toUserRoleDto(User user);
@Mappings({
@Mapping(source = "id", target = "userId"),
@Mapping(source = "username", target = "name"),
@Mapping(source = "role.roleName", target = "roleName")
})
List<UserRoleDto > convertList(List<user> list);
} Test... In a test class :
As can be seen from the above example , Use MapStruct It's a lot easier .
边栏推荐
- An email many years ago
- Jincang database kingbasees SQL language reference manual (3.1.1.6. boolean type, 3.1.1.7. bit string type)
- 第十九周作业
- Thesis reading: Pyramid scene parsing network
- HCIP第三天学习笔记
- 金仓数据库 KingbaseES SQL 语言参考手册 (3.1.1.13. JSON 类型)
- 内存管理页面属性
- 什么是ECS框架?讲解 + 实战带你入门ECS框架
- iptables 端口转发
- 【机器学习】在线学习 - Online Learning
猜你喜欢
随机推荐
[programming training 10] tic tac toe chess + password strength level
What is the ECS framework? Explain + practice to get you started ECS framework
端口转发工具 rinetd
金仓数据库 KingbaseES SQL 语言参考手册 (3.1.1.9. 网络地址类型)
[programming training 5] continuous maximum sum + statistical palindrome
hcip动态路由实验(RIP)
Memory management page properties
Kingbasees SQL language reference manual of Jincang database (3.1.1.4. date / time type)
【机器学习】自动编码器 - Autoencoder
【RT-Thread】nxp rt10xx 设备驱动框架之--uart搭建和使用
Jincang database kingbasees SQL language reference manual (3.1.1.6. boolean type, 3.1.1.7. bit string type)
JS regular advanced code to understand
安装g2opy框架
Viewpager conflict resolution
金仓数据库 KingbaseES SQL 语言参考手册 (3.1.1.13. JSON 类型)
MGRE/OSPF综合实验
金仓数据库 KingbaseES SQL 语言参考手册 (3.1.1.12. XML类型)
IIC读写EEPROM
Hcip third day learning notes
群晖7.1使用SHR添加硬盘








