com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败

时间:2017-04-29 10:50:35

标签: java mysql hibernate jpa

我想在插入一些数据时不断收到错误

项目类

@Entity
@NamedQueries({
        @NamedQuery(name = "Project.findAll",
         query = "SELECT p FROM Project p"),
        @NamedQuery(name = "Project.findByTitle",
                query = "SELECT p FROM Project p WHERE p.title = :title")
})
public class Project implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int projectId;

    @Column
    private String title;
    @Column
    private String description;
    @Column
    private Date projectDate;

    @ManyToOne
    @JoinColumn(name = "projectStatusId")
    private ProjectStatus projectStatus;

    @OneToMany(mappedBy = "projectMemberId",fetch = FetchType.EAGER)
    private List<ProjectMember> memberList = new ArrayList<ProjectMember>();

    /**
     * Setters and Getters
     */
}

ProjectMember Class

@Entity
@NamedQueries({
        @NamedQuery(name = "ProjectMember.findAll",
                query = "SELECT pm FROM ProjectMember pm"),
        @NamedQuery(name = "ProjectMember.findByProject",
                query = "SELECT pm FROM ProjectMember pm WHERE pm.project = :project"),
        @NamedQuery(name = "ProjectMember.findByUser",
                query = "SELECT pm FROM ProjectMember pm WHERE pm.user = :user"),
        @NamedQuery(name = "ProjectMEmeber.findByUserAndProject",
                query = "SELECT pm FROM ProjectMember pm  WHERE pm.user = :user AND pm.project = :project")
})

public class ProjectMember implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int projectMemberId;


    @Column
    private Date activationDate;
    @Column
    private Date lastActiveDate;

    @ManyToOne
    @JoinColumn(name = "memberStatusId")
    private MemberStatus memberStatus;

    @ManyToOne
    @JoinColumn(name = "projectId")
    private Project project;


    @ManyToOne
    @JoinColumn(name = "memberRoleId")
    private MemberRole memberRole;

    @ManyToOne
    @JoinColumn(name = "userId")
    private User user;

    /**
     * Setter and Getter
     */
}

我的运作方式

ProjectController类

public String createProject(){
    project.setProjectDate(new Date());
    project.setProjectStatus(new ProjectStatusFacade().findByStatus("active"));

    ProjectMember projectMember = new ProjectMember();
    projectMember.setMemberStatus(new MemberStatusFacade().findByStatus("accepted"));
    projectMember.setMemberRole(new MemberRoleFacade().findByRole("team leader"));
    projectMember.setActivationDate(new Date());
    projectMember.setUser(userSession.getUser());

    new ProjectFacade().create(project);
    System.out.print(project);
    projectMember.setProject(project);
    new ProjectMemberFacade().create(projectMember);

    userSession.setUser(new UserFacade().findById(userSession.getUser().getUserId()));
    return "index?faces-redirect=true";
}

这就是我最终得到的结果

 Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ... more exceptions

    Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ... more exceptions

    Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ...more exceptions

    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`goent`.`projectmember`, CONSTRAINT `FKfyw2iinfhhsbrmqbu1sr7l93q` FOREIGN KEY (`projectMemberId`) REFERENCES `project` (`projectId`))
        ... more exceptions

    15:51:06,449 ERROR [io.undertow.request] (default task-4) UT005023: Exception handling request to /hibernate/pages/project-add-member.xhtml: javax.servlet.ServletException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ... more exceptions

    Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ... more exceptions

    Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ...more exceptions
    Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
        ... more exceptions

    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`goent`.`projectmember`, CONSTRAINT `FKfyw2iinfhhsbrmqbu1sr7l93q` FOREIGN KEY (`projectMemberId`) REFERENCES `project` (`projectId`))
        ... more exceptions

使用:Java,JPA,Hibernate,MySQL5.7

3 个答案:

答案 0 :(得分:0)

例外原因是:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`goent`.`projectmember`, CONSTRAINT `FKfyw2iinfhhsbrmqbu1sr7l93q` FOREIGN KEY (`projectMemberId`) REFERENCES `project` (`projectId`))

您的操作违反了项目成员表中 projectMemberId 列的外键约束,该列引用了项目的 projectId 根据您定义的规格表。

答案 1 :(得分:0)

这是最有可能发生的事情。

Project实体中,您告诉持久性提供程序始终急切地获取ProjectNames

@OneToMany(mappedBy = "projectMemberId",fetch = FetchType.EAGER)
private List<ProjectMember> memberList = new ArrayList<ProjectMember>();

然后在保存方法中,您正在创建ProjectName并使用Project填充它。这很好,但Project中的列表不包含新创建的ProjectName

必须在双方都设置依赖关系,因此最终您需要在方法中执行以下操作:

project.getMemberList().add(projectName);

答案 2 :(得分:0)

谢谢大家,最后我可以解决这个问题。问题出在 Project 类中,它是关于不正确的映射。我没有告诉变量在其他类中映射,而是指向该类的PK。

我写了这个

项目类

@ManyToOne
    @JoinColumn(name = "projectStatusId")
    private ProjectStatus projectStatus;
而不是这个

//Correct code
@ManyToOne
    @JoinColumn(name = "project")
    private ProjectStatus projectStatus;

在此更改后,代码开始运行良好。