How properly map multiple level inheritance object

Viewed 64

i have the following classes

public class Store   {
     @JsonProperty("name")
      private String name;
      
      @JsonProperty("pets")
      @Valid
      private List<Pet> pets = new ArrayList<>();
      
      getters/setters
      }

Pet model

JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = Cat.class, name = "cat"),
  @JsonSubTypes.Type(value = Dog.class, name = "dog"),
  @JsonSubTypes.Type(value = Pig.class, name = "pig"),
})

public class Pet   {
  /**
   * Gets or Sets evidenceType
   */
  public enum TypeEnum {
    CAT("cat"),
    
    DOG("dog"),
    
    PIG("pig");
    }
}

Type classes

public class Cat extends Pet{
}
public class Dog extends Pet{
}
public class Pig extends Pet{
}

How properly map this classes?

@Mapper
public interface StoreEntityMapper {
StoreEntity toStoreEntity(Store store);
Store to Store(StoreEntity store);

}
@Mapper
public interface PetEntityMapper {
PetEntity toPetEntity(Pet pet);
Pet to Pet (PetEntity pet);

}
1 Answers

So end up having one mapper and manually mapping the type classes. Do not create 2 mappers, Pet logic get overwritten by auto generated mapper impl

@Mapper
public interface StoreEntityMapper {

StoreEntity toStoreEntity(Store store);
Store to Store(StoreEntity store); 

default PetEntity toPetEntity(Pet pet){
   if(Pet instanceof Dog ){
      Dog animal = new Dog();
      animal.setName(pet.getName());
       set all prop 
      return animal;
   }
  if(Pet instanceof Pig){
       Pig animal = new Pig();
      animal.setName(pet.getName());
       set all prop 
      return animal;
   }
     if(Pet instanceof Cat ){
      Cat animal = new Cat();
      animal.setName(pet.getName());
       set all prop 
      return animal;
   }
  return null;
}
default Pet to Pet (PetEntity pet){
if(Pet instanceof DogEntity ){
      DogEntity animal = new DogEntity();
      animal.setName(pet.getName());
       set all prop 
      return animal;
   }
  if(PetEntity instanceof PigEntity){
       PigEntity animal = new PigEntity();
      animal.setName(pet.getName());
       set all prop 
      return animal;
   }
     if(PetEntity instanceof CatEntity ){
      CatEntity = new CatEntity();
      animal.setName(pet.getName());
       set all prop 
      return animal;
   }
  return null;
}
Related