我正在使用mapstruct并遇到以下问题-
我有一个DTO家长:
{
"parentId":1,
"child":{
"id":1,
"name":"firstBorn"
}
}
这是 DTO 和服务器类:
@Data
public class ParentDTO {
int parentId;
ChildDto child;
}
@Data
public class ChildDTO{
int id;
ChildDto child;
}
POJO是:
@Data
public class Parent{
int parentId;
Child child;
}
@Data
public class Child{
int parentId;
int id;
String name;
}
所以我正在使用 Mapstruct 来映射这两者:
@Mapper( unmappedTargetPolicy = ReportingPolicy.IGNORE)
class ParentMapper {
@Mappings({
@Mapping(source = "parentId", target = "child.parentid"),
@Mapping(source = "name", target = "child.name")
})
Parent map(ParentDto source);
}
我想创建实例子级当且仅当它存在于父级中时,否则我希望它为 null,我如何实现这一目标?
当子项处于空状态时出现问题
{
"parentId":123
}
您可以创建一个方法并将逻辑放入其中
/**
* If you are sure that the parentDto will never be NULL, you can remove the @NonNull annotation (lombok.NonNull)
* I use the AllArgsConstructor to create a new instance of Child,
* I pass null to id (I think you will generate the id when you will save the Child entity in the DB), if not, you can change it with parentDto.getChild().getId()
*/
protected Child mapChild(@NonNull ParentDto parentDto) {
return parentDto.getChild() != null ? new Child(parentDto.getParentId(), null, parentDto.getChild().getName()) : null;
}
然后使用它来映射子实体
@Mapping(target = "child", expression = "java(mapChild(source))")
abstract Parent map(ParentDto source);
所以现在映射器将如下所示:
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ParentMapper {
@Mapping(target = "child", expression = "java(mapChild(source))")
abstract Parent map(ParentDto source);
protected Child mapChild(@NonNull ParentDto parentDto) {
return parentDto.getChild() != null ? new Child(parentDto.getParentId(), null, parentDto.getChild().getName()) : null;
}
}