[英]How properly map multiple level inheritance object
我有以下課程
public class Store {
@JsonProperty("name")
private String name;
@JsonProperty("pets")
@Valid
private List<Pet> pets = new ArrayList<>();
getters/setters
}
寵物模型
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");
}
}
類型類
public class Cat extends Pet{
}
public class Dog extends Pet{
}
public class Pig extends Pet{
}
如何正確映射這些類?
@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);
}
所以最終擁有一個映射器並手動映射類型類。 不要創建 2 個映射器,寵物邏輯會被自動生成的映射器 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.