我正在尝试在Jpa中建立一对一的关系。当我运行该程序时,抛出异常
ERROR: Cannot add or update a child row: a foreign key constraint fails (`ngsharma`.`student`, CONSTRAINT `FK8nqh8nm4hrwx9hlqwhxf6kfen` FOREIGN KEY (`laptop_lid`) REFERENCES `laptop` (`lid`))
学生
@Entity(name = "student")
public class Student {
@Id
private int rollno;
private String name;
@OneToOne
private Laptop laptop;
/*Setter & Getter*/
}
笔记本电脑
@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>
运行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();
最佳答案
在您的示例中,您尝试保存一个student
实体,对于该实体,数据库中不存在laptop
关联。根据您提供的代码片段,这两个实例都是新创建的。因此,根据数据库级别的外部约束,您尝试从laptop
表中引用student
表;其中带有引用的laptop
的相应id
行不存在。
如果在持久化laptop
实体的同时还持久化关联的student
实体,则将解决问题。您需要做的唯一修改就是将@OneToOne
关系更新为:
@OneToOne(cascade=CascadeType.PERSIST)
private Laptop laptop;
这将起作用;因为它还会将
laptop
实体以及student
实体本身插入数据库中。