Maciej Dobrowolski
Maciej Dobrowolski

Reputation: 12140

JPA unidirectional ManyToMany - duplicated positions in when retrieving list

I had following entities in my project:

With folowing relations:

and everything worked fine.

When I changed last relation to:

AccountGroup object read from database looks strange. If given AccountItem had three AccountSegments, then I have three the same AccountItems in AccountGroup.

A shot from debugger can possibly tell it better than I can: SS from debugger

As you can see, accountMapperItems list has four positions instead of two. First pair is a duplicate each having the same variables. (second is similar, not shown on screenshot).

Below I paste entities code fragments:

class AccountGroup {
    ...
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "group")
    private List<AccountItem> accountMapperItems;
    ....
}

class AccountItem {
    ...
    @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.REFRESH, CascadeType.MERGE })
    @JoinTable(
        joinColumns={@JoinColumn(name="ACCOUNT_ITEM_ID", referencedColumnName="ID")},
        inverseJoinColumns={@JoinColumn(name="SEGMENT_ID", referencedColumnName="ID")})
    private Set<Segment> segmentSet;

    @ManyToOne
    private AccountGroup group;
    ...
}

AccountSegment does not have any links.

Does anyone know why is it retriving accountMapperItems list one position per AccountSegment?

The problem is not duplicate entries in jointable! I have double checked it.

Update

@Fetch (FetchMode.SELECT)

solved the case, further explanations are available in post mentioned in the answer.

Upvotes: 1

Views: 926

Answers (1)

David Levesque
David Levesque

Reputation: 22451

Make sure all your entities implement hashCode() and equals(). These methods are used by some collections (like Sets) to uniquely identify elements.

Edit: If that doesn't solve it, then I think the duplicates are most likely caused by the FetchType.EAGER. This answer explains it well. Try removing the FetchType.EAGER to see if it makes any difference.

Upvotes: 3

Related Questions