【问题标题】:How to map object references in mapstruct using JHipster?如何使用 JHipster 在 mapstruct 中映射对象引用?
【发布时间】:2019-01-04 18:21:34
【问题描述】:

假设您使用这样的 JDL 脚本为带有帖子的博客创建了一个 JHipster 应用程序,并且您想要一个显示其中的帖子的 BlogDTO(以及一个显示每个帖子的评论的 BlogDTO):

entity Blog {
    creationDate Instant required
    title String minlength(2) maxlength(100) required
}

entity Post {
    creationDate Instant required
    headline String minlength(2) maxlength(100) required
    bodytext String minlength(2) maxlength(1000) required
    image ImageBlob
}

entity Comment {
    creationDate Instant required
    commentText String minlength(2) maxlength(1000) required
}


// RELATIONSHIPS:
relationship OneToMany {
    Blog to Post{blog required}
    Post{comment} to Comment{post(headline) required}
}

// Set pagination options
paginate all with pagination

// DTOs for all
dto * with mapstruct

// Set service options to all except few
service all with serviceClass

// Filtering
filter *

Jhipster 将使用它们的 DTO 创建您的 Blog、Post 和 Comment 实体,并假设您不想用 Posts 填充 Blog 或用 cmets 填充 Posts,因此您的 BlogMapper 将如下所示:

@Mapper(componentModel = "spring", uses = {})
public interface BlogMapper extends EntityMapper<BlogDTO, Blog> {

    @Mapping(target = "posts", ignore = true)
    Blog toEntity(BlogDTO blogDTO);


    default Blog fromId(Long id) {
        if (id == null) {
            return null;
        }
        Blog blog = new Blog();
        blog.setId(id);
        return blog;
    }
}

使用这样的 BlogDTO:

public class BlogDTO implements Serializable {

    private Long id;

    @NotNull
    private Instant creationDate;

    @NotNull
    @Size(min = 2, max = 100)
    private String title;
//GETTERS, SETTERS, HASHCODE, EQUALS & TOSTRING

任何人都可以帮助修改代码,以便 BlogDTO 将显示帖子(而 PostDTO 将显示评论)。谢谢

PD:因为我更改了 Annotation 以包含 PostMapper 类 @Mapper(componentModel = "spring", uses = {PostMapper.class})

并且 @Mapping(target = "posts", ignore = false) 为 FALSE 但它不起作用。 API 示例 (Swagger) 看起来不错,但 PostDTO 为空(即使数据存在)。

【问题讨论】:

    标签: jhipster mapstruct


    【解决方案1】:

    Set&lt;PostDTO&gt; posts; 添加到您的 BlogDTO 并将 Set&lt;CommentDTO&gt; comments; 添加到您的 PostDTO。还要为 DTO 文件中的这些字段添加 getter 和 setter。然后在您的映射器中,确保 BlogMapper 使用 PostMapper 并且 PostMapper 使用 CommentMapper。

    您可能还需要在 Blog.java 中的 posts 字段和 Post.java 中的 comments 字段上配置缓存注释以适应您的用例。使用NONSTRICT_READ_WRITE,更新缓存可能会有延迟,从而导致 API 返回过时的数据。

    【讨论】:

    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 2018-01-18
    • 2020-05-08
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2021-02-17
    • 2021-02-24
    相关资源
    最近更新 更多