Mapstructs实现对象拷贝:
- 单个对象拷贝(默认只拷贝属性名和方法名都相同的值),当属性名或者属性类型不同时可使用@Mapping注解进行映射
- List拷贝
- List嵌套List拷贝
代码示例
import lombok.AllArgsConstructor;
import lombok.Data;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Mapstructs实现实现拷贝:
* 1、单个对象拷贝
* 2、List拷贝
* 3、List嵌套拷贝
* 4、自定义拷贝规则
* MapSturct 是一个生成类型安全, 高性能且无依赖的 JavaBean 映射代码的注解处理器,编译后会生产相应代码,路径为
* target/generated-sources/annotations/BeanCopierUtilImpl.java
*/
@Mapper
interface BeanCopierUtil {
BeanCopierUtil INSTANCE = Mappers.getMapper(BeanCopierUtil.class);
/**
* 单个对象转化
* @param userDto
* @return
*/
@Mappings({
@Mapping(target = "userName", source = "user_name")
})
UserVo toVo(UserDto userDto);
/**
* List集合拷贝,支持嵌套,需要定义UserDto到UserVo的转化
*/
List<UserVo> toVo(List<UserDto> userList);
}
public class MapstructTest {
public static void main(String[] args) {
List<UserDto> userDtoList = Stream.of(
new UserDto("1","张三",5),
new UserDto("2","李四",6)
).collect(Collectors.toList());
List<UserVo> result = BeanCopierUtil.INSTANCE.toVo(userDtoList);
System.out.println(userDtoList);
System.out.println(result);
}
}
@Data
@AllArgsConstructor
class UserDto {
private String id;
private String user_name;
private Integer user_age;
}
@Data
class UserVo {
private String id;
private String userName;
private Integer userAge;
}
运行结果
[UserDto(id=1, user_name=张三, user_age=5), UserDto(id=2, user_name=李四, user_age=6)]
[UserVo(id=1, userName=张三, userAge=null), UserVo(id=2, userName=李四, userAge=null)]
Pom.xml引入依赖包
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<mapstruct.version>1.5.5.Final</mapstruct.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
备注
编译之后自动生成方法实现,位置为: