I have standard entities and dto's.
Entities:
public class Type extends DefaultEntity {
int id;
String name
...
}
public class Attribute extends DefaultEntity{
int id;
String name;
Type type;
...
}
and DTO's
public class TypeDto extends DefaultDto {
int id;
String name;
...
}
public class AttributeDto extends DefaultDto{
int id;
String name;
TypeDto type;
....
}
when I create this Mapper:
@Mapper
public interface AttributeDtoConverter {
AttributeDto convert(Attribute source);
}
Mapstruct generates:
public class AttributeDtoConverterImpl implements AttributeDtoConverter {
@Override
public AttributeDto convert(Attribute source) {
if ( source == null ) {
return null;
}
AttributeDto attributeDto = new AttributeDto();
attributeDto.setId( source.getId() );
attributeDto.setName( source.getName() );
attributeDto.setCode( source.getCode() );
attributeDto.setType( typeToTypeDto( source.getType() ) );
return attributeDto;
}
// Here is the problem
protected TypeDto typeToTypeDto(Type type) {
if ( type== null ) {
return null;
}
TypeDto dictionaryDto = new TypeDto();
typeDto.setId( type.getId() );
typeDto.setName( type.getName() );
return typeDto;
}
}
I want to exclude from mapping all properties of target object if they are subclasses of DefaultDto (or exclude all properties of source object if they are subclasses of DefaultEntity).
I know I can exclude every property by name @Mapping(target="type", ignore=true), but for large classes with much more dependencies it will we very annoying. And changing model with this approach becomes hell.
Can I somehow exclude all properties by their superclass?
Update
I tried @Condition:
@Mapper
public interface AttributeDtoConverter {
AttributeDto convert(Attribute source);
@Condition
default boolean needToMap(Object value){
return ! (value instanceof DefaultDto || value instanceof DefaultEntity);
}
}
It works but I don't like how the generated code looks like:
public class AttributeDtoConverterImpl implements AttributeDtoConverter {
@Override
public AttributeDto convert(Attribute source) {
if ( source == null ) {
return null;
}
AttributeDto attributeDto = new AttributeDto();
if ( needToMap( attributeDto.getId() ) ) {
attributeDto.setId( source.getId() );
}
if ( needToMap( attributeDto.getName() ) ) {
attributeDto.setName( source.getName() );
}
if ( needToMap( attributeDto.getCode() ) ) {
attributeDto.setCode( source.getCode() );
}
if ( needToMap( attributeDto.getType() ) ) {
attributeDto.setType( typeToTypeDto( source.getType() ) );
}
return attributeDto;
}
...
}