首页 > 解决方案 > 如何在 JPA 中删除树状结构中的对象?

问题描述

我的应用程序可以存储文件夹和文件,每个文件夹都可以有一些子文件夹并有一个parent_id指向其父文件夹的属性。此 JPA-Object 的代码如下所示,也是数据库表的屏幕截图。

现在我想添加一个删除功能,删除一个包含所有内容的文件夹。例如 deleteSubFolder-3应该删除 SubFolder4、-5、-6 和它本身。

我在属性上使用 Cascade.Type=REMOVE 进行了尝试parent,并将其添加@transactional到存储库中的删除方法中。但我得到这个错误:

Caused by: org.postgresql.util.PSQLException: ERROR: update or delete on table "cloud_folder" violates foreign key constraint "fk715hn6f0nslmk97oftbbtm0ab" on table "cloud_folder"
  Detail: Key (id)=(5) is still referenced from table "cloud_folder".

文件夹对象:

@Entity
public class CloudFolder {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @ManyToOne
    private CloudFolder parent;  

// Getter and Setter
}

文件夹存储库:

public interface CloudFolderRepository extends JpaRepository<CloudFolder, Integer> {

    CloudFolder findByParentId(Integer id);

    @Transactional
    void deleteByParentId(Integer id);

}

我的文件夹表的图片在这里:

标签: javasqlhibernatespring-bootjpa

解决方案


推荐阅读