Java MapStruct:基于(布尔)值排除属性
我知道MapStruct可以忽略未映射的属性和特定的目标属性,但是是否可以基于属性的实际值来导出属性 我有布尔字段,只有当它们为false时,我才想排除它们 提前谢谢 例如: 实体:Java MapStruct:基于(布尔)值排除属性,java,mapstruct,Java,Mapstruct,我知道MapStruct可以忽略未映射的属性和特定的目标属性,但是是否可以基于属性的实际值来导出属性 我有布尔字段,只有当它们为false时,我才想排除它们 提前谢谢 例如: 实体: @Entity @Table(name = "vehicle") @Getter @Setter public class Vehicle { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; priva
@Entity
@Table(name = "vehicle")
@Getter @Setter
public class Vehicle {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private boolean hasWheels;
private boolean hasWings;
private boolean hasBrakes;
}
DTO:
MapStruct映射器:
@Mapper(componentModel = "spring")
public interface VehicleMapper {
// Entity to DTO:
VehicleDTO toVehicleDTO(Vehicle vehicle);
List<VehicleDTO> toVehicleDTOs(List<Vehicle> vehicles);
// DTO to Entity:
Vehicle toVehicle(VehicleDTO vehicleDTO);
}
@Mapper(componentModel=“spring”)
公共接口车辆标签{
//实体到DTO:
车辆到车辆到(车辆);
车辆清单TOS(车辆清单);
//向实体发送的DTO:
车辆对车辆(车辆对车辆对车辆);
}
我只想在布尔变量的值为“false”时完全排除它们。您可以使用Jackson忽略空字段
@JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO
在下面的方法中,如果值为false,不要只将DTO中的布尔字段设置为false
//实体到DTO:
车辆到车辆到(车辆)
您还可以使用Spring BeanUtils来复制和重写copyProperties方法
public static String[] gePropertyNames(Object source) {
final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
return Stream.of(wrappedSource.getPropertyDescriptors())
.map(FeatureDescriptor::getName)
.filter(propertyName -> {
if(wrappedSource.getPropertyValue(propertyName) != null && wrappedSource.getPropertyValue(propertyName) instanceof Boolean){
Boolean value = (Boolean) wrappedSource.getPropertyValue(propertyName);
if(value){
return false;
}else{
return true;
}
}else{
return false;
}
}).toArray(String[]::new);
}
// then use Spring BeanUtils to copy and ignore properties using our function
public static void myCopyProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, gePropertyNames(src));
}
我不确定在MapStruct中是否有一种干净的方法。一种方法是在mapstruct中使用表达式。我想下面的代码可能会有所帮助
@Mapper(componentModel = "spring")
public interface VehicleMapper {
@Mapping(target = "hasWheels", expression = "java((hasWheels)?hasWheels:false)")
Vehicle toVehicle(VehicleDTO vehicleDTO);
}
但是,您使用的基本类型布尔变量具有“false”默认值,尽管您设置或忽略了它。MapStruct的概念是。默认情况下(当发生隐式转换时),它会在将源值分配给目标之前检查源值是否为
null
。还有一种方法是使用选项nullValueCheckStrategy=nullValueCheckStrategy.ALWAYS
,当源是非原语时,它将始终包括null
检查,除非在源bean上定义了源存在检查器
说了这么多。因为在您的示例中,源属性是基本布尔属性,所以可以通过为这些字段添加状态检查来实现这一点。这样就不需要表达式了
e、 g.对于DTO
@Getter @Setter
public class VehicleDTO {
private String name;
private boolean hasWheels;
private boolean hasWings;
private boolean hasBrakes;
public boolean hasHasWheels() {
return hasWheels;
}
}
使用此功能,实现将首先检查DTO是否具有
hasWheels
,然后将其设置为目标。请共享代码我添加了一个示例
@Getter @Setter
public class VehicleDTO {
private String name;
private boolean hasWheels;
private boolean hasWings;
private boolean hasBrakes;
public boolean hasHasWheels() {
return hasWheels;
}
}