0

I have a problem with the following many to many relationship

Two entities Person and Group

mapping in Person

@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "person_group",
        joinColumns = {@JoinColumn(name = "person_id")},
        inverseJoinColumns = {@JoinColumn(name = "group_id")})
private Set<Group> groups = new HashSet<>();

mapping in Group

@ManyToMany(mappedBy = "groups" , fetch = FetchType.LAZY, cascade = {CascadeType.MERGE})
@JsonIgnore
public Set<Person> getPeople() {
    if (people == null){
        people = new HashSet<>();
    }
    return people;
}

We have a spring batch job for inserting, updating People

At the start we use raw sql to persist all the potential groups as this is predefined reference data.

For each Person we get a group by id and associate the Person and Group on both directions.

At the end of the batch job we save and flush the list of People.

The problem is we are ending up with duplicate entries in the Group table.

Any help would be greatly appreciated.

Thanks

  • Based on the code posted, it looks like you are possibly mixing field and method level annotations. If the `@Id` annotation is on a field in your `Group` entity then, by default, the JPA mappings on the association will be ignored. https://stackoverflow.com/a/942285/1356423 – Alan Hay Jun 14 '18 at 14:24
  • @AlanHay Thanks for the suggestion but we have no annotations on any of our fields. Still trying to debug through the code. – Ashley Callaghan Jun 14 '18 at 14:30
  • `@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable(name = "person_group", joinColumns = {@JoinColumn(name = "person_id")}, inverseJoinColumns = {@JoinColumn(name = "group_id")}) private Set groups = new HashSet<>();` What is that? A JPA annotation on a field is it not? – Alan Hay Jun 14 '18 at 14:31
  • @AlanHay Sorry was looking at the source code and looked at the wrong annotation. Thanks – Ashley Callaghan Jun 14 '18 at 14:34

0 Answers0