[英]MapStruct spring boot
有誰知道為什么 mapStruct 不允許 DTO class 的元素少於 ENTITY class。
例如我有這個實體:
public class Provider {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(cascade=CascadeType.ALL, mappedBy="provider")
private Set<Product> products;
}
和 dto:
public class ProviderDTO {
private Long id;
private String name;
}
ps:當我將 List 添加到 DTO 時,一切正常。 但我希望我的 DTO class 只包含我想要的屬性,而不是實體 class 中的屬性。
當您的源對象和目標對象不相同時,您需要在映射器類的映射方法中定義差異。
如果源和目標 object 具有不同的屬性名稱,您需要定義源的哪個屬性名稱將映射到目標的哪個屬性名稱。
如果目標沒有屬性但源有,則需要在映射方法上為該屬性指定忽略。
@Mapping(目標=“產品”,忽略=真)
查看錯誤消息,您似乎在自己的模塊中擁有 DTO 對象、實體對象和映射器。 但是當將它們添加到最終產品時,您使用的版本與所需的功能不匹配。
正在使用的生成的映射器需要 DTO class 中的列表 object。但是提供的 DTO 信息沒有這個。 這意味着映射器需要更新,以便它知道 DTO class 沒有這個字段。
在代碼中:
// DTO module version 2
class DTO {
private String field1;
private String field2;
// removed: private List<String> list1;
// leaving out setters/getters
}
// Entity module version 1
class Entity {
private String field1;
private String field2;
private List<String> list1;
// leaving out setters/getters
}
// Mapper module version 1 with dependencies on:
// DTO module version 1
// Entity module version 1
interface Mapper {
DTO EntitytoDto(Entity source);
}
@Generated
class MapperImpl {
DTO EntitytoDto(Entity source) {
// mapping code for field1, field2 and list1.
}
}
上面代碼的最終結果是NoSuchMethodError
當它嘗試 map list1
時。
你想要的是:
// Mapper module version 2 with dependencies on:
// DTO module version 2
// Entity module version 1
interface Mapper {
DTO EntitytoDto(Entity source);
}
@Generated
class MapperImpl {
DTO EntitytoDto(Entity source) {
// mapping code for field1 and field2.
}
}
希望這有助於解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.