![](/img/trans.png)
[英]Is it possible to use one propertyMap for ModelMapper (in spring boot) to map in both directions (DTO to Entity and Entity to DTO)?
[英]Spring boot: Custom mapping between DTO and Entity using ModelMapper
我想 map 我的 DTO ( CreateOrUpdatePostRequest
) 到我的實體Post
。
但我不知道如何 go 因為我的實體有這樣的關系:
@Entity
@Table(name = "POSTS")
@Data
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "post_id")
private int id;
private String title;
private String description;
@Temporal(TemporalType.DATE)
@Column(name = "expire_at")
private Calendar expireAt;
@ManyToOne
@JoinColumn(name = "CATEGORY_ID")
private Category category;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "TAG_POST", joinColumns = {
@JoinColumn(name = "post_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "tag_id",
nullable = false, updatable = false) })
private Set<Tag> tags = new HashSet<Tag>(0);
}
一篇文章可以有一個類別和多個標簽。
這是我的 DTO:
@Data
public class CreateOrUpdatePostRequest {
@NotNull
@Size(min = 10, max = 30)
private Sting title;
@NotNull
@Size(min = 50, max = 600)
private String description
@NotNull
@ValidDateString
private String expireAt;
@NotNull
private Category category;
@NotNull
private List<TagDTO> tags;
public List<Integer> getTagIds() {
return this.getTags().stream().map(TagDTO::getId).collect(Collectors.toList());
}
}
問題:我的問題是我必須為某些屬性應用特定的映射邏輯以確保標簽有效,例如:
post.setTags(tagService.findAllByIds(request.getTagIds()));
所以我想應該在我的PostService
中完成映射,知道我必須訪問tagService
? 我的意思是我不能在我的CreateOrUpdateRequest
中真正創建一個toEntity
方法。
有沒有辦法保留所有屬性的默認 ModelMapper 行為,但使用外部服務為某些屬性指定特定行為?
例如,如果我的 DTO 內部有一個需要上述相同行為的 DTO,例如在TagDTO
中,如何繼續?
我不確定你是否已經經歷過 MapStruct 的事情,但你可以在這里詳細看看。
https://medium.com/uphill-engineering-design/deep-dive-into-mapstruct-spring-7ddd8dac3d6d
這是基於邊緣意見的,但仍然是我對此的看法:
PostService
是一個 Spring 管理的 Bean(可能用@Service
注釋),所以我想說應該在那里完成映射,使用TagService
來獲取Tag
。TagDto
應該由TagService
映射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.