我正在尝试将Entity对象映射到DTO以转移到前端应用程序。 查询返回包含institutionName和internalName的List,我想将它们映射到DTO中的modelsInstitution和modelsInternalName列表。 我被我的mappers课程困住了。
以下是我的实体:
@Entity
@DynamoDBTable(tableName = "Inventory")
public class Inventory
{
@Id
private String id;
private String institutionName;
private String internalName;
private String lanAdapter;
public Inventory() {
}
public Inventory(String Id,String InstitutionName, String LanAdapter, String InternalName)
{
this.id = Id
this.lanAdapter = LanAdapter;
this.institutionName = InstitutionName;
this.internalName = InternalName;
}
@DynamoDBHashKey(attributeName = "Id")
public String getId()
{
return id;
}
public void setId(String id)
{
this.id=id;
}
@DynamoDBAttribute(attributeName = "InstitutionName")
public String getInstitutionName()
{
return institutionName;
}
public void setInstitutionName(String InstitutionName)
{
this.institutionName = InstitutionName;
}
@DynamoDBAttribute(attributeName = "LanAdapter")
public String getLanAdapter()
{
return lanAdapter;
}
public void setLanAdapter(String LanAdapter)
{
this.lanAdapter = LanAdapter;
}
@DynamoDBAttribute(attributeName = "InternalName")
public String getInternalName()
{
return internalName;
}
public void setInternalName(String InternalName)
{
this.internalName = InternalName;
}
}
下面是我的DTO对象:
public class FilterDto
{
private List<String> modelsInstitution;
private List<String> modelsInternalName;
public FilterDto(List<String> modelsInstitution, List<String> versions) {
super();
this.modelsInstitution = modelsInstitution;
this.modelsInternalName = modelsInternalName;
}
public List<String> getModelInstitution() {
return modelsInstitution;
}
public void setModelInstitution(List<String> modelsInstitution) {
this.modelsInstitution = modelsInstitution;
}
public List<String> getModelInternalName() {
return modelsInternalName;
}
public void setModelInternalName(List<String> modelsInternalName) {
this.modelsInternalName = modelsInternalName;
}
}
Mapper类:
我的映射不正确,我错过了如何将列表中的实体映射到DTO。
@IterableMapping(elementTargetType = Inventory.class)
@Mappings({
@Mapping(target="modelsInstitution", expression="java(inventory.getInstitution())"),
@Mapping(target="modelsInternalName", expression="java(inventory.getInternalName())")
})
FilterDto InventoryToFilterDTO1(List<Inventory> inventory);
答案 0 :(得分:1)
使用MapStruct无法真正做到这一点。我建议你手动进行这种映射。
您的映射可能如下所示:
public interface MyMapper {
default FilterDto InventoryToFilterDTO1(List<Inventory> inventory) {
List<String> institutions = new ArrayList<>(inventory.size());
List<String> names = new ArrayList<>(inventory.size());
for(Inventory inv: inventory) {
institutions.add(inv.getInstitution());
names.add(inv.getInternalName()));
}
return new FilterDto(institutions, names);
}
}
从理论上讲,使用@Context
,@AfterMapping
,@BeforeMapping
和@ObjectFactory
可能有办法使用MapStruct执行此操作。但是,这会复杂得多。