I would like to know when and why I should use the helper method 'public void addLocation(Location location)' like in the following example when saving an entity that contains a many to many relationship with another entity:
@Entity
@Table(name = "scope")
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Scope implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private @Getter @Setter Long id;
@Column(name = "name")
private @Getter @Setter String name;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER)
@JoinTable(name = "scope_location", joinColumns = @JoinColumn(name = "scope_id"), inverseJoinColumns = @JoinColumn(name = "location_id"))
Set<Location> locations = new HashSet<>();
public void addLocation(Location location){
locations.add(location);
location.scopes.add(this);
}
}
I have seen many examples that use the 'add' method and many that don't.