使用 MapStruct
1.以maven形式添加
<org.mapstruct.version>1.3.0.Final</org.mapstruct.version>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
2.举例: UserEntity 转换成UserVO(不包含password)
创建映射Mapper
@Mapper
public interface ModelMapper {
UserVO covertVo(UserEntity userEntity);
}
ModelMapper mapper = Mappers.getMapper(ModelMapper.class);
UserVO userVO = mapper.covertVo(userEntity);
不同字段映射
@Data
public class UserEntity {
private Long id ;
private String username;
private String password;
private String nickname;
}
@Data
public class UserVO {
private Long id ;
private String username;
private String nick;
}
映射文件编辑
@Mapper
public interface ModelMapper {
@Mapping(source = "nickname" , target = "nick")
UserVO covertVo(UserEntity userEntity);
}
多个
@Mapper
public interface ModelMapper {
@Mapping(source = "Id" , target = "id")
@Mapping(source = "nickname" , target = "nick")
UserVO covertVo(UserEntity userEntity);
}
@Mapper
public interface ModelMapper {
@Mappings({
@Mapping(source = "Id", target = "id"),
@Mapping(source = "nickname", target = "nick")
})
UserVO covertVo(UserEntity userEntity);
}
网友评论