0

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.

Gal Sosin
  • 714
  • 7
  • 27
  • You got an answer already but just as an [example](https://stackoverflow.com/q/48882268/6413377) what kind of problems can occur if you allow adding nested objects directly - without this kind of adder methods - and forget to set the relations explicitly to both sides or relationship. – pirho Feb 25 '18 at 14:42

1 Answers1

1

The helper method ensures that both sides of the bi-directional relation are updated. The scope has the location and the location has the scope and that is true immediately in memory, just as if you hade saved and then loaded everything in a new session. Doing that in the helper method ensures that it is always done as long as the helper method is used everywhere. Furthermore some classes return immutable sets (wrapping the original versions) from the public get methods and then you have no choice. If you want to add you must use the add method. I like that.

Updating the other side manually also works. Partly it is a matter of style and preference. However, I would recommend picking a convention and following it for a given project.

ewramner
  • 5,810
  • 2
  • 17
  • 33