Hibernate实体级联删除父或子

时间:2018-06-18 15:44:17

标签: java spring hibernate jpa cascade

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

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()与path []的上下文发生异常[请求处理失败;嵌套异常是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:无法执行带有根本原因的语句

如何删除父类别?

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

你可以致电

  。

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

1 个答案:

答案 0 :(得分:0)

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

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

然后

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

现在您可以删除parentCategory

相关问题