Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct map correct instance of object based on target type

How to correct map different classes with same parent

spring DTO jackson objects

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type",
    )
@JsonSubTypes(value = {
            @JsonSubTypes.Type(value = B.class, name = "TypeB"),
            @JsonSubTypes.Type(value = C.class, name = "TypeC")
})
abstract class A {
   Type type;
   String id;
}


class B extends A {
    String name;  
}


class C extends A {
   String description;
}

Entity class contains all fields

class myEntity {
    Type type;
    String id;
    String name;  
    String description;
} 

MapStruct mapper

public abstract class IntegrationMapper  {
    public A toDto(MyEntity myEntity);
    public MyEntity fromDto(A integrationDTO)  
}

How I can create different instances B or C into toDto depends on type value ?

I use smth like that

public abstract class IntegrationMapper {
    public A toDto(MyEntity myEntity) {
        if(myEntity.type == TypeB) {
            return toB(myEntity);
        } else if (myEntity.type == TypeC) {
            return toC(myEntity);            
        }
    }

    public MyEntity fromDto(A a)  {
        if(a instanceOf B) {
            return fromDto((B) a);
        } else if (a instanceOf C) {
            return fromDto((C) a);
        }
    }

    protected B toB(MyEntity myEntity);
    protected C toC(MyEntity myEntity);

    protected MyEntity fromDto(B c);
    protected MyEntity fromDto(C c);

}

But I suspect that it can be done better with ObjectFactory or smth like that

to avoid long if statement and creation new method for each new child of A

like image 936
Kaiser Avatar asked Jul 27 '26 13:07

Kaiser


1 Answers

If you want to perform the mapping for the fields in B and C you will have to create methods for them. MapStruct is a code generation so it doesn't know anything about the runtime types.

Your current approach is the way to go for what you are looking for. I don't think that using ObjectFactory can help you out. The only way it can help you out is if you want to map MyEntity to the base A. In such case it will generate mapping only between the base and the entity, which is not what you are looking for.

There is an open feature request (#131) that can generate those instance of checks for you.

like image 138
Filip Avatar answered Jul 29 '26 05:07

Filip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!