Использование параметра qualBy или qualbBameName в MapStruct не работает - PullRequest
0 голосов
/ 24 марта 2020

У меня есть несколько сущностей

  • post

public class Post {

    @Id
    @SequenceGenerator(name = "jpaSequence.Post",
            sequenceName = "SEQUENCE_POST",
            allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaSequence.Post")
    private Long id;
    private String subject;

    @OneToMany(mappedBy = "post", fetch = FetchType.LAZY)
    private List<Comment> comments = new ArrayList<>();

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn
    private User user;

  • комментарий
@Entity
@Table(name = "comments")
public class Comment {

    @Id
    @SequenceGenerator(name = "jpaSequence.Comment",
            sequenceName = "SEQUENCE_COMMENT",
            allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaSequence.Comment")
    private Long id;

    private String reply;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn
    private Post post;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn
    private User user;

  • user
@Entity
@Table(name = "users")
public class User {

    @Id
    @SequenceGenerator(name = "jpaSequence.User",
            sequenceName = "SEQUENCE_USER",
            allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaSequence.User")
    private Long id;

    private String name;
    private String email;
  • postDto
public class PostDto {


    private Long id;
    private String subject;

    private List<CommentDto> comments = new ArrayList<>();


    private UserDto user;
  • commentDto
public class CommentDto {


    private Long id;

    private String reply;

    private PostDto post;


    private UserDto user;
  • userDto
public class UserDto {

    private Long id;

    private String name;
    private String email;
  • mapper
@Mapper(componentModel = "spring")
public interface PostMapper {

    Post postDtoToPostEntity(PostDto dto);

    @Mapping(target = "post.comments", ignore = true)
    CommentDto toCommentDto(Comment entity);

    @Mapping(target = "comments", source = "entity.comments", qualifiedBy = CommentListDtoAnnotation.class)
    PostDto postEntityToPostDto(Post entity);


    @CommentListDtoAnnotation
    default Iterable<CommentDto> commentListEntityToCommentListDto(Iterable<Comment> source) {

        Iterable<CommentDto> collect = StreamSupport.stream(source.spliterator(), false)
                .map(this::toCommentDto)
                .peek(dto -> dto.setPost(null))
                .collect(Collectors.toList());

        return collect;
    }

    Iterable<Post> postListDtoToPostListEntity(Iterable<PostDto> list);

    Iterable<PostDto> postListEntityToPostListDto(Iterable<Post> list);
}
  • commentMapper
@Mapper(componentModel = "spring")
public interface CommentMapper {

    Comment commentDtoToCommentEntity (CommentDto dto);

    @Mapping(target = "post.comments", ignore = true)
    CommentDto commentEntityToCommentDto(Comment entity);

    Iterable<Comment> commentListDtoToCommentListEntity(Iterable<CommentDto> list);

    Iterable<CommentDto> commentListEntityToCommentListDto(Iterable<Comment> list);

}
  • аннотация
import org.mapstruct.Qualifier;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Qualifier
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface CommentListDtoAnnotation {
}

Но, Произошло преобразование, и я получаю:

Это ответ.

{
    "id": 1,
    "subject": "JPA Entity Graph In Action",
    "comments": [
        {
            "id": 1,
            "reply": "Nice !!",
            "post": {
                "id": 1,
                "subject": "JPA Entity Graph In Action",
                "comments": [],
                "user": {
                    "id": 1,
                    "name": "user1",
                    "email": "user1@test.com"
                }
            },
            "user": {
                "id": 2,
                "name": "user2",
                "email": "user2@test.com"
            }
        },
        {
            "id": 2,
            "reply": "Cool !!",
            "post": {
                "id": 1,
                "subject": "JPA Entity Graph In Action",
                "comments": [],
                "user": {
                    "id": 1,
                    "name": "user1",
                    "email": "user1@test.com"
                }
            },
            "user": {
                "id": 3,
                "name": "user3",
                "email": "user3@test.com"
            }
        }
    ],
    "user": {
        "id": 1,
        "name": "user1",
        "email": "user1@test.com"
    }
}

Update_1

  • сервис
@Service
public class PostReadServiceImpl implements PostReadService {

    private PostRepository repository;

    private PostWithoutNestedLevelsTransformers transformer;


    @Autowired
    public PostReadServiceImpl(PostRepository repository,
                               PostWithoutNestedLevelsTransformers transformer) {
        this.repository = repository;
        this.transformer = transformer;
    }



    @Override
    public PostDto getEntryById(Long id) {

        Post entity = findEntry(id);

        PostDto postDto = this.transformer.transformEntityToDto(entity);

        return postDto;
    }


    private Post findEntry(Long id){

        return this.repository.findById(id).orElseThrow(() -> new RuntimeException("Post not found!"));
    }

    @Transactional
    @Override
    public Iterable<PostDto> getListPosts() {

        Iterable<Post> posts = findListPosts();

        Iterable<PostDto> postDtoList = this.transformer.transformListEntityToDtoList(posts);

        return postDtoList;
    }

    private Iterable<Post> findListPosts(){

        Iterable<Post> posts = this.repository.findAll();

        return posts;
    }


    private Iterable<Comment> pickUpComment (List<Comment> comments ){

        List<Comment> listComment = new ArrayList<>();

           for (Comment comment : comments){

            Comment conversionComment = moveData(comment);

            listComment.add(conversionComment);
        }

        return listComment;

    }


    private Comment moveData(Comment comment){
        Comment conversionComment = new Comment();

        String commentReply = comment.getReply();
        Long idUser = comment.getId();

        conversionComment.setId(idUser);
        conversionComment.setReply(commentReply);

        return conversionComment;

    }
}
  • трансформатор

@Component
public class PostTransformer {

    private PostMapper mapper;

    @Autowired
    public PostTransformer(PostMapper mapper) {
        this.mapper = mapper;
    }

    public PostDto transformEntityToDto(Post entity){

        PostDto postDto = this.mapper.postEntityToPostDto(entity);

        return postDto;
    }


    public Post transformDtoToEntity(PostDto dto){

        return this.mapper.postDtoToPostEntity(dto);
    }

    public Iterable<PostDto> transformListEntityToDtoList(Iterable<Post> listEntity){

        Iterable<PostDto> postDtoList = this.mapper.postListEntityToPostListDto(listEntity);

        return postDtoList;
    }

    public Iterable<Post> transformListDtoToEntityList(Iterable<PostDto> listDto){

        return this.mapper.postListDtoToPostListEntity(listDto);
    }

}

Метод должен быть выполнен:


    @CommentListDtoAnnotation
    default Iterable<CommentDto> commentListEntityToCommentListDto(Iterable<Comment> source) {

Но это не работает.

В комментарии к полю вложенное поле - post - должно быть = null ...

Я не понимаю, я делаю это неправильно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...