I want to remove points and PointOperations in Point so to remove such entities (bidirectional mapping, OneToMany) I need to use this approach: Spring Data REST + JPA remove from OneToMany collection [not owner side]
public class Path {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "path", cascade = CascadeType.ALL, orphanRemoval = true)
List<Point> points;
public void removePoint(Point point) {
point.setPath(null);
this.getPoints().remove(point);
}
public class Point{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "point", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private List<PointOperation> operations;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "path_id", foreignKey = @ForeignKey(name = "FK_point_path"), nullable = false)
private Path path;
public void removePointOperation(PointOperation pointOperation) {
pointOperation.setPoint(null);
this.getOperations().remove(pointOperation);
}
public class PointOperation {
@Column(nullable = false, updatable = false)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "point_id", foreignKey = @ForeignKey(name = "FK_point_point_operation"), nullable = false)
private Point point;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "window_id", foreignKey = @ForeignKey(name = "FK_point_window"))
private Window window;
}
This approach seems to be working - I have to avoid ConcurrentModificationException:
if (window.getPath().getPoints() != null) {
List<Point> copiedPoints = new ArrayList<>(window.getPath().getPoints());
for (Point point : copyPoints) {
if (point.getOperations() != null && !point.getOperations().isEmpty()) {
List<PointOperation> pointOperations = new ArrayList(point.getOperations());
for (PointOperation pointOperation : pointOperations) {
point.removePointOperation(pointOperation);
}
}
window.getPath().removePoint(point);
}
}
But my question is if this approach is correct? I want t remove nested entities that are in bidirectional mapping