简体   繁体   中英

How to map only selected fields using mapstruct

How do I map only selected fields with mapStructand return thenm as response.

Ex:

class Location {
         
   String street;
          
   String unit;
    
   int postCode;
 
 }

public class Car {
 
    private Location location;.
}

public class CarDto {

  private Location location;

}

Now I can map them using:

@Mapper
public interface CarMapper {
 
    CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); 
 
   CarDto returnObject =  CarDto carToCarDto(Car car); 
}

Now, returnObject will contain location which will have street, unit and postCode .

But, I want to expose just the street and postCode with returnObject.location.

How can I expose only those selected fields?

When you want to only map certain fields and ignore everything else you can use BeanMapping#ignoreByDefault .

eg

@Mapper
public interface CarMapper {

    CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); 
 
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target = "street", source = "location.street")
    @Mapping(target = "postCode", source = "location.postCode")
    CarDto carToCarDto(Car car); 

}

By using @BeanMapping(ignoreByDefault = true) you are ignoring all properties. And by using the @Mapping you are defining which properties you want to map.

If you want to ignore some field in target object, just simple indicate it in MapStruct @Mapping annotation, like below:

@Mapping(target = "location.postCode", ignore = true)
CarDto carToCarDto(Car car);

Change your CarDto like this:

public class CarDto {

   String street;
   int postCode;

}

And in your mapper:

@Mapper
public interface CarMapper {
 
   CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); 
 
   @Mapping(source = "location.street", target = "street")
   @Mapping(source = "location.postCode", target = "postCode")
   CarDto returnObject =  CarDto carToCarDto(Car car); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM