如何避免使用null
ModelMapper
值从源复制到目的地
我尝试了下面的代码,但是它始终在目标位置覆盖null
值
public class EntityMapperTest {
public static void main(String[] args) {
TripDto tripDto = new TripDto();
tripDto.setDriverID("123");
tripDto.setRegNo("12345");
//tripDto.setTripStatus("completed");
Trip trip = new Trip();
trip.setTripID("ids");
trip.setTripStatus("active");
EntityMapperTest entityMapper = new EntityMapperTest();
Trip newTrip = (Trip) entityMapper.convertToEntitySkipNull(tripDto,trip);
System.out.println("status "+newTrip.getTripStatus());
System.out.println("trip ID "+newTrip.getTripID());
System.out.println(newTrip.getDriverID());
System.out.println(newTrip.getRegNo());
System.out.println("********TRIP******");
System.out.println(trip.getTripID());
System.out.println(trip.getTripStatus());
System.out.println(trip.getDriverID());
System.out.println(trip.getRegNo());
}
public Object convertToEntitySkipNull( TripDto src,Trip dest) {
ModelMapper mapperObj=new ModelMapper();
mapperObj.typeMap(src.getClass(),dest.getClass()).setPropertyCondition(Conditions.isNotNull());
mapperObj.getConfiguration().setSkipNullEnabled(true).setAmbiguityIgnored(true);
return mapperObj.map(src,dest.getClass());
}
}
输出:
status null // this should have been active, but null is copied
trip ID null // this should have been ids, but null is copied
123
12345
********TRIP******
ids
active
null
null
我错过了什么吗?另外,我也尝试过以下方法,但是没有运气。
public Object convertToEntitySkipNull( TripDto src,Trip dest) {
ModelMapper mapperObj=new ModelMapper();
mapperObj.typeMap(src.getClass(),dest.getClass()).setPropertyCondition(Conditions.isNotNull());
mapperObj.typeMap(src.getClass(),dest.getClass()).addMappings(mapping -> mapping.when(context -> {
System.out.println(context.getSource());
if(context.getSource() != null){
return true;
}
return false;
}
).map(TripDto::getTripStatus,(destination, value) -> destination.setTripStatus((String) value)));
mapperObj.getConfiguration().setSkipNullEnabled(true).setAmbiguityIgnored(true);
return mapperObj.map(src,dest.getClass());
}
行家:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.2</version>
</dependency>