简体   繁体   中英

Cannot add or update a child row: a foreign key constraint fails using Hibernate Framework

Is there anybody can help me to solve this problem?

I am trying to save student's record one at a time in my system and save it to different tables in my database but i got error when saving it.

It involves 4 Classes namely Personalinfo.java (Parent Class) , Student.java (Child Class-extends Personalinfo.java), Students_Credentials.java (Links to Student.java) and ManageStudent.class (contains method that saves the student's record)

Error

Database Design

Heres the Code:

PersonalInfo.java

//PersonalInfo.java

@Entity
@Table(name="personal_info")
@Inheritance(strategy=InheritanceType.JOINED)  
public class Personalinfo {
  @Id
  @GeneratedValue
  @Column(name="personalid")
  private long personalUID;
  @Column(name="lastname")
  private String lastname;
  @Column(name="firstname")
  private String firstname;
  @Column(name="middlename")
  private String middlename;
  @Column(name="Suffix")
  private String suffix;
  @Column(name="gender")
  private String gender;
  @Column(name="homeaddress")
  private String homeaddress;
  @Column(name="birthdate")
  private String birthdate;
  @Column(name="bloodtype")
  private String bloodtype;
  @Column(name="contactno")
  private String contactno;
  @Column(name="email")
  private String email;
  @Column(name="cplastname")
  private String cplastname;
  @Column(name="cpfirstname")
  private String cpfirstname;
  @Column(name="cpmiddlename")
  private String cpmiddlename;
  @Column(name="cphomeaddress")
  private String cphomeaddress;
  @Column(name="cpcontactno")
  private String cpcontactno;
  @Column(name="photo")
  private Blob photo;
  @Column(name="note")
  private String note;

  //(Netbeans)Automated Get & Set Method..

}

Student.java

//Student.java

@Entity
@Table(name="student")
@PrimaryKeyJoinColumn(name="personalid") 

public class Student extends Personalinfo {

    @Column(name="studentidno",unique=true,nullable=false)
    private String stud_id;

    @Column(name="gradeschool")
    private String grade_school;

    @Column(name="gs_aygraduated")
    private String gs_ay_graduated;

    @Column(name="highschool")
    private String high_school;

    @Column(name="hs_aygraduated")
    private String hs_ay_graduated;

    @Column(name="college")
    private String College;

    @Column(name="c_aygraduated")
    private String c_ay_graduated;

    //(Netbeans)Automated Get & Set Method..

}

Students_Credentials.java

@Entity
@Table(name="students_credentials")

public class Students_Credentials {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="studentscredentialsid",unique=true,nullable=false)
    private long stud_credentials_id;

    @Column(name="credentialsnamesubmitted")
    private String credentials_name_submitted;


    @ManyToOne(optional = false)
    @JoinColumn(name="studentidno")
    private Student Student;

   //(Netbeans)Automated Get & Set Method..

}

ManageStudent.java

public static void addStudent(String Lastname,String Firstname,String Middlename,String Suffix,String ContactNo.......)
  {
    Session session = NewHibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try
    {
        //***personal_info table(Parent Class) and student table(Student Class extends Personal_info Class) ***

        tx = session.beginTransaction();   
        Student stud=new Student();
        stud.setLastname(Lastname);
        stud.setFirstname(Firstname);
        stud.setMiddlename(Middlename);
        stud.setSuffix(Suffix);
        stud.setGender(Gender);
        stud.setGender(Gender);
        stud.setHomeaddress(HomeAddress);
        stud.setBirthdate(Birthdate);
        stud.setContactno(ContactNo);
        stud.setEmail(Email);
        stud.setCplastname(CPLastname);
        stud.setCpfirstname(CPFirstname);
        stud.setCpmiddlename(CPMiddlename);
        stud.setCphomeaddress(CPHomeAddress);
        stud.setCpcontactno(CPContactNo);
        stud.setPhoto(Photo);
        stud.setNote(Note);
        stud.setStud_id(IDno);
        stud.setGrade_school(GradeSchool);
        stud.setGs_ay_graduated(GSAYGraduated);
        stud.setHigh_school(HighSchool);
        stud.setHs_ay_graduated(HSAYGraduated);
        stud.setCollege(College);
        stud.setC_ay_graduated(CollAYGraduated);


        //***students_credentials table(Students_Credentials class)***

        Students_Credentials Stud_Cred0=new Students_Credentials("Form 138");
        Students_Credentials Stud_Cred1=new Students_Credentials("NSO");
        Students_Credentials Stud_Cred2=new Students_Credentials("HD");

        Stud_Cred0.setStudent(stud);
        Stud_Cred1.setStudent(stud);
        Stud_Cred2.setStudent(stud);

        session.persist(stud);

        session.persist(Stud_Cred0);
        session.persist(Stud_Cred1);
        session.persist(Stud_Cred2);


        tx.commit();
    }
    catch (HibernateException e)
    {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
    }
    finally
    {
      session.close();
    }
  }

This got too long for a comment and I want to format some code. This is not a full answer, this is me speculating on how this issue might be resolved.

Your error is being caused, because Hibernate is trying to save the StudentCredentials object, without having an id on the Student object it is attached too. Either the ID doesn't exist, or it doesn't match the ID on the student object for some reason.

I've never managed Hibernate transactions and sessions myself. I've always used Hibernate within Spring, which managed the transaction for me.

If I had to guess (and I stress, this is a complete guess) I'd say you have to do the following.

create Student
save student
commit **this should put a generated id on the student record**
set Student on Student_Credentials objects
save Student Credentials objects

Just as a note, if you are using Hibernate stand alone, then that's your decision, but if you have the option to integration Hibernate with something like Spring, to manage all the minutiae and boilerplate for you, you'll usually make your life easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM