Skip to content

@Condition on shared super-type #3209

@mrhydejc

Description

@mrhydejc

Use case

I would like to define a @condition on every properties of my Entities. (Hibernate related)
All entities extends Bean class. When defining a condition on Bean, mapstruct apply condition to source (as source and property extends Bean, it choose source).
I would like to apply it to the property instead.

Example :

public class A extend Bean {
    private B b;
}

public class ADTO  {
    private BDTO b;
}

public class B extend Bean {
    [...]
}

@Mapper
public interface AMapper extends Converter<A, ADTO> {

    ADTO convert(A bean);

    @Condition
    public static boolean isLazyBeanAvailable(Bean bean) {
    if (bean == null) {
      return false;
    }
    return Hibernate.isInitialized(bean);
  }
}

Generate :

@Component
public class AMapperImpl implements AMapper {

    @Override
    public ADTOconvert(A bean) {
        if ( bean == null ) {
            return null;
        }

        ADTO.Builder adto= ADTO.newBuilder();

        if ( isLazyBeanAvailable( bean ) ) {
            adto.setB( bean.getB() );
        }

       [...]
}

Generated Code

Apply isLazyBeanAvailable to bean.getB() instead of bean.
Could be :

@Component
public class AMapperImpl implements AMapper {

    @Override
    public ADTOconvert(A bean) {
        if ( bean == null ) {
            return null;
        }

        ADTO.Builder adto= ADTO.newBuilder();

        if ( isLazyBeanAvailable( bean.getB() ) ) {
            adto.setB( bean.getB() );
        }

       // ommited
}

May be a parameter on @condition could tel mapstruct to use property instead of source in ambigious cases.

Possible workarounds

Define condition on actual type instrad of super type :

@Condition
  public static boolean isLazyBeanAvailable(B bean) {
    if (bean == null) {
      return false;
    }
    return Hibernate.isInitialized(bean);
  }

MapStruct Version

1.5.3.Final

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions