【问题标题】:Hibernate entity cascade deletion parent or childHibernate实体级联删除父或子
【发布时间】:2018-06-18 15:44:17
【问题描述】:

我有一些关于“级联”的问题, 在我的项目中,我有类别类,每个类都可以是父类或子类。但是我在同一个类中定义了一个父或子。父子之间存在一对多的关系。这是我的实体类

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.*;

import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@EqualsAndHashCode(exclude = {"recipes","categories","parentCategory","childrenCategory"})
@Entity
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

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

    private String categoryName;

    private String categoryDescription;

    private String categoryUrl;


    @OneToMany(mappedBy = "parentCategory",cascade = CascadeType.ALL)
    private Set<Category> childrenCategory = new HashSet<>();

    @ManyToOne
    private Category parentCategory;

    private boolean menuActive;

    @ManyToMany(mappedBy = "categories")
    Set<Recipe> recipes = new HashSet<>();

    public Category addChildren(Category category){
        this.getChildrenCategory().add(category);
        category.setParentCategory(this);
        return this;
    }

}

我的问题是; 当我删除子类别时,它的成功没有问题。如果父类别有子类别,我无法删除父类别。

错误信息;

servlet [dispatcherServlet] 在路径 [] 的上下文中的 Servlet.service() 引发异常 [请求处理失败;嵌套异常是 org.springframework.dao.DataIntegrityViolationException:无法执行语句; SQL [不适用];约束 ["FKBPI63NYEL12J6UG0D7S6BUAKX: PUBLIC.CAT_RECIPE FOREIGN KEY(CATEGORY_ID) REFERENCES PUBLIC.CATEGORY(ID) (5)"; SQL 语句: 从 id=? 的类别中删除[23503-197]];嵌套异常是 org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

如何删除父类别?

解决方案

public void removeChildren(Category childCategory){
    childCategory.setParentCategory(null);
}

你可以打电话

category.get().getChildrenCategory().forEach(category.get()::removeChildren);

【问题讨论】:

    标签: java spring hibernate jpa cascade


    【解决方案1】:

    这是一种双向关系。因此,您将需要从双方删除关联。像这样的:

    public void removeChildren(Category childCategory){
        this.getChildrenCategory().remove(childCategory);
        childCategory.setParentCategory(null);
    }
    

    然后

    parentCategory.getSubCategories().forEach(parentCategory::remove);

    现在您可以删除parentCategory

    【讨论】:

    • 例如在这个方法中:当我用 for 循环迭代时 parentCategory 有三个 subCat 第一次迭代是好的,但第二次抛出空异常?
    • 我修好了,这个解决方案应该是; public void removeChildren(Category childCategory){ childCategory.setParentCategory(null); } 谢谢
    猜你喜欢
    • 2020-06-25
    • 2018-12-04
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多