I have 2 classes with @ManyToMany relationship
first class: Clip
second class: Location
the main idea is that a clip can be available in several locations
this is the clip class.
@Entity
@Table(name = "CLIP")
public class Clip {
private Long id;
private List<Location> locations;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToMany( )
@JoinTable(name="CLIP_LOCATION",joinColumns=@JoinColumn(name="CLIP_ID",nullable=false),inverseJoinColumns=@JoinColumn(name="LOCATION_ID",nullable=false) )
@ForeignKey(name="FK_CLIP_LOCATION",inverseName="FK_LOCATION_CLIP")
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
}
this is the Location class
@Entity
@Table(name = "LOCATION")
public class Location {
}
this is not a bi-directional relationship
My Question:
When i remove a location from the user interface , i want the relevant row in the join-table to be removed automatically,
Can i do that?
what annotation should i use?
Note that the Location class and Clip class are used in other relationships too
Thanks
Maayan
Am i using the wrong relationship?
This is not possible. You have to remove the location from the lists of locations before deleting the location. Since your association is unidirectional, you’ll have to execute a query to find all the clips available on the location, and remove the location from each clip.
Another option is to execute a native SQL query to remove rows from the join table, but keep in mind that the entities aready loaded in the session won’t be aware of the change.