微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring Boot + JPA (Hibernate) - 如何使用 OneToMany 双向映射删除嵌套实体

如何解决Spring Boot + JPA (Hibernate) - 如何使用 OneToMany 双向映射删除嵌套实体

我想删除 Point 中的点和 PointOperations,以便删除这样的实体(双向映射,OnetoMany)我需要使用这种方法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",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;
}

这种方法似乎有效 - 我必须避免 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);
            }
        }

但我的问题是这种方法是否正确?我不想删除双向映射中的嵌套实体

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。