Spring ModelMapping error appeared when I try to convert Post to PostDTO,if I replace @Data annotation with @Getter, @Setter, it works perfectly

Viewed 52
package com.springboot.blog.entity;

import lombok.*;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "posts")
public class Post {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Long id;

    @Column(name = "title", nullable = false)
    private String title;

    @Column(name = "description", nullable = false)
    private String description;

    @Column(name = "content", nullable = false)
    private String content;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Comment> comments = new HashSet<>();
}

Here is the Post class

package com.springboot.blog.payload;

import lombok.Data;

import java.util.Set;

@Data
public class PostDTO {
    private Long id;
    private String title;
    private String description;
    private String content;
    private Set<CommentDTO> comments;
}

Here is PostDTO class.

@Override
    public PostDTO getPost(Long id) {
        Post temp_post = postRepository.findById(id).
                orElseThrow(() -> new ResourceNotFoundException("Post", "Id", id));
        return mapToDTO(temp_post);
    }

    private PostDTO mapToDTO(Post post) {
        return modelMapper.map(post, PostDTO.class);
    }

I used mapToDTO method to convert post to postDTO.

But When I test it, the error message appeared.

{"timestamp":"2022-04-30T14:03:03.369+00:00","status":500,"error":"Internal Server Error","trace":"org.modelmapper.MappingException: ModelMapper mapping errors:\n\n1) Error mapping com.springboot.blog.entity.Post to com.springboot.blog.payload.PostDTO\n\n1 error\n\tat org.modelmapper.internal.Errors.throwMappingExceptionIfErrorsExist(Errors.java:380)\n\tat org.modelmapper.internal.

========================================================================================

** But when I replace the @Data annotation in class Post with @Getter, @Setter. It works perfectly! **

0 Answers
Related