简体   繁体   中英

Hibernate: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

I'm trying to create one to one relationship in Jpa. When I run this program throw the Exception

ERROR: Cannot add or update a child row: a foreign key constraint fails (`ngsharma`.`student`, CONSTRAINT `FK8nqh8nm4hrwx9hlqwhxf6kfen` FOREIGN KEY (`laptop_lid`) REFERENCES `laptop` (`lid`))

Student

@Entity(name = "student")
public class Student {

    @Id 
    private  int rollno;
    private String name;    
    @OneToOne 
    private Laptop laptop;

    /*Setter & Getter*/
}

Laptop

@Entity(name = "laptop")
public class Laptop {

    @Id
    private int lid;
    private String laptopName;

    /*Setter & Getter*/
}

Hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ngsharma</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MariaDBDialect</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Run CLass

    Configuration configuration = 
            new Configuration().configure()
                                                    .addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);

    SessionFactory sessionFactory = configuration.buildSessionFactory();

    Session session = sessionFactory.openSession();

    Laptop laptop = new Laptop();
    laptop.setLid(101);
    laptop.setLaptopName("Mac Nootbook");

    Student student = new Student();
    student.setRollno(1);
    student.setName("Shri Krishan");
    student.setLaptop(laptop);

     Serializable serializable = session.save(student);
     System.out.println("Test Code : "  + serializable);

     session.beginTransaction().commit();

In your example, you are trying to save a student entity, for which laptop association does not exist in database. Both instances are newly created as far as understand from the code snippet you provided. Hence, according to the foreign constraint at database level, you are trying to reference laptop table from within student table; where the corresponding laptop row with the referenced id does not exist.

If you also persist the associated laptop entity while persisting the student entity your problem will be solved. The only modification you need to do is to update the @OneToOne relation as:

    @OneToOne(cascade=CascadeType.PERSIST)  
    private Laptop laptop;

This will work; since it will also insert the laptop entity to the database along with the student entity itself.

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