Mike
Mike

Reputation: 1097

How to map object references in mapstruct using JHipster?

Let's say that you create a JHipster app for a Blog with Posts using a JDL script like this and you want to have a BlogDTO that shows the Posts within it (and a BlogDTO that shows the Comments each Post has):

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 will create your Blog, Post and Comment entities with their DTOs and makes the assumption that you do not want to populate the Blog with the Posts or the Posts with the comments, so your BlogMapper will look like this:

@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;
    }
}

with a BlogDTO like this:

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

Can anybody help to modify the code so the BlogDTO will show the Posts (and the PostDTO will show the Comments). Thanks

PD: Because I changed the Annotation to include the PostMapper class @Mapper(componentModel = "spring", uses = {PostMapper.class})

And the @Mapping(target = "posts", ignore = false) to FALSE but it does not work. The API example (Swagger) look fine, but then the PostDTO is null (even when the data is there).

Upvotes: 0

Views: 2268

Answers (1)

Jon Ruddell
Jon Ruddell

Reputation: 6362

Add a Set<PostDTO> posts; to your BlogDTO and a Set<CommentDTO> comments; to your PostDTO. Also add getters and setters for those fields in the DTO files. Then in your mappers, make sure that the BlogMapper uses PostMapper and that the PostMapper uses CommentMapper.

You may also need to configure the caching annotations on the posts field in Blog.java and the comments field in Post.java to fit your use-case. With NONSTRICT_READ_WRITE, there can be a delay in updating the cache, resulting in stale data returned by the API.

Upvotes: 2

Related Questions