【发布时间】: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