0

I have two entities defined. Both of them are connected through a bidirectional @OneToMany. Here are my two entities

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    //Constructors, getters and setters removed for brevity

    public void addComment(PostComment comment) {
        comments.add(comment);
        comment.setPost(this);
    }

    public void removeComment(PostComment comment) {
        comments.remove(comment);
        comment.setPost(null);
    }
}

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

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

    //Constructors, getters and setters removed for brevity

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof PostComment )) return false;
        return id != null && id.equals(((PostComment) o).getId());
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

I am using Spring Data JPA to fetch / save entities. Saving works fine and for example if I save 1 post and 4 post comments I can see the entries in the database. The database I am using is PostgreSQL. When I am fetching all the posts through my repository using the findAll method, then I receive the post with the 4 comments.

The issue is when I am fetching only one post through the getOne method, the post is found, but for some reason the entity contains 7 post comments. The first entry is duplicated 3 times and the second one is duplicated two times.

I don't understand why this is happening and how can I fix this. Any help is appreciated.

Thanks

CipQuestion
  • 391
  • 4
  • 11

1 Answers1

0

You need to change List to Set.

@OneToMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true)
private Set<PostComment> comments = new HashSet<>();
Sagar Ahuja
  • 637
  • 10
  • 10
  • But why does that happen? This seems like a workaround. – CipQuestion Dec 10 '19 at 21:39
  • 1
    Have a look at this. (https://developer.jboss.org/wiki/HibernateFAQ-AdvancedProblems?_sscc=t#Hibernate_does_not_return_distinct_results_for_a_query_with_outer_join_fetching_enabled_for_a_collection_even_if_I_use_the_distinct_keyword). It is better explained here (https://stackoverflow.com/questions/1995080/hibernate-criteria-returns-children-multiple-times-with-fetchtype-eager/1995244#1995244) – Sagar Ahuja Dec 11 '19 at 06:22