从具有多个实体的映射器中获取一个实体
get an Entity from a mapper with several Entities
假设您有两个实体在数据库 Ent1 和 Ent2 中定义对象,以及一个描述二合一的 DTO。
我的带有 MapStruct EntitiesDtoMapper 的映射器看起来像:
@Mapper
interface EntitiesDtoMapper{
DTO EntitiesToDto(Ent1 ent1, Ent2 ent2);
//It is possible to do this?
Ent1 DtoToEnt1(DTO dto);
}
我想从 DTO 中获取 Ent1 和 Ent2,这可能吗?
我认为将一个 DTO 分成两个实体(如果它们未嵌入)不是最佳做法。如果是这样,我建议手动将 dto 映射到两个实体,因为这是最简单和最快的方法。
对谁感兴趣;这是可能的,但要注意实体的参数名称。
这里有一个例子:
@Data @Entity
public class Ent1{
public Ent1() {}
String id;
String name;
}
@Data @Entity
public class Ent2{
public Ent2() {}
String id;
String name;
}
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class DTO{
String id1,id2,name1,name2;
}
@Mapper
public interface EntitiesDtoMapper{
EntitiesIcspDtoMapper INSTANCE = Mappers.getMapper(EntitiesDtoMapper.class);
@Mappings({
@Mapping(source="ent1.id", target = "id1"),
@Mapping(source="ent1.name", target = "name1"),
@Mapping(source="ent2.id", target = "id2"),
@Mapping(source="ent2.name", target = "name2")
})
DTO EntitiesToDto(Ent1 ent1, Ent2 ent2);
@Mappings({
@Mapping(source="id1", target = "id"),
@Mapping(source="name1", target = "name"),
})
Ent1 DtoToEnt1(DTO dto);
@Mappings({
@Mapping(source="id2", target = "id"),
@Mapping(source="name2", target = "name"),
})
Ent2 DtoToEnt2(DTO dto);
}
假设您有两个实体在数据库 Ent1 和 Ent2 中定义对象,以及一个描述二合一的 DTO。
我的带有 MapStruct EntitiesDtoMapper 的映射器看起来像:
@Mapper
interface EntitiesDtoMapper{
DTO EntitiesToDto(Ent1 ent1, Ent2 ent2);
//It is possible to do this?
Ent1 DtoToEnt1(DTO dto);
}
我想从 DTO 中获取 Ent1 和 Ent2,这可能吗?
我认为将一个 DTO 分成两个实体(如果它们未嵌入)不是最佳做法。如果是这样,我建议手动将 dto 映射到两个实体,因为这是最简单和最快的方法。
对谁感兴趣;这是可能的,但要注意实体的参数名称。
这里有一个例子:
@Data @Entity
public class Ent1{
public Ent1() {}
String id;
String name;
}
@Data @Entity
public class Ent2{
public Ent2() {}
String id;
String name;
}
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class DTO{
String id1,id2,name1,name2;
}
@Mapper
public interface EntitiesDtoMapper{
EntitiesIcspDtoMapper INSTANCE = Mappers.getMapper(EntitiesDtoMapper.class);
@Mappings({
@Mapping(source="ent1.id", target = "id1"),
@Mapping(source="ent1.name", target = "name1"),
@Mapping(source="ent2.id", target = "id2"),
@Mapping(source="ent2.name", target = "name2")
})
DTO EntitiesToDto(Ent1 ent1, Ent2 ent2);
@Mappings({
@Mapping(source="id1", target = "id"),
@Mapping(source="name1", target = "name"),
})
Ent1 DtoToEnt1(DTO dto);
@Mappings({
@Mapping(source="id2", target = "id"),
@Mapping(source="name2", target = "name"),
})
Ent2 DtoToEnt2(DTO dto);
}