SpringBoot JPA提示:Cannot add or update a child row: a foreign key constraint fails/MySQL :1452 添加外键失败

虾米姐 阅读:735 2021-03-31 13:19:54 评论:0

问题描述:一个简单的Spring Data JPA应用程序,包含一个树形结构类对象Permission,测试树形结构类型父子关系时,提示如下错误信息

ERROR: Cannot add or update a child row: a foreign key constraint fails (alter table permission add constraint FKifxah7gioyuisbm17akbaoua7 foreign key (permision_parent_id) references permission (permission_id)) 
 

错误信息分析:

permission表中的有的permision_parent_id不属于permission表中的permission_id

实体对象:

package com.zzg.entity; 
 
import lombok.Getter; 
import lombok.Setter; 
 
import java.util.HashSet; 
import java.util.List; 
import java.util.Set; 
 
import javax.persistence.CascadeType; 
import javax.persistence.Entity; 
import javax.persistence.FetchType; 
import javax.persistence.Id; 
import javax.persistence.JoinColumn; 
import javax.persistence.ManyToOne; 
import javax.persistence.OneToMany; 
 
/** 
 *  
 * @author zzg 
 * 
 */ 
@Getter 
@Setter 
@Entity 
public class Permission { 
 
    @Id 
    private Integer permissionId; 
    private String permissionName; 
    private String permissionZh; 
    private String permissionPath; 
    private String permisionIcon; 
    private String permisionComponent; 
     
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)    
    @JoinColumn(name="permision_parent_id")   
    private Permission parent; 
    // 子菜单项 
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", fetch = FetchType.EAGER)   
    private Set<Permission> child  = new HashSet<Permission>(); ; 
} 

错误数据:

正确数据:

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号