【发布时间】:2019-06-28 11:52:37
【问题描述】:
我开始学习spring mvc。我正在做一些练习,我遇到了一个逻辑错误。在我的示例中,我在 spring mvc 中有 2 个实体类。在那里我的代码 school_ıd 是主键。当我尝试从学校列表中删除一所学校时,我给出了这样的错误
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
实体学校:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="school_id")
private int schoolId;
@Column(name="school_name")
private String schoolName;
public int getSchoolId() {
return schoolId;
}
public void setSchoolId(int schoolId) {
this.schoolId = schoolId;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
实体学生
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
@OneToOne
@JoinColumn(name="school_id")
private School school;
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
校方删除方法:
@GetMapping("/deleteSchool")
public String deleteSchool(@RequestParam("schoolID") int
theSchoolId) {
schoolService.deleteSchool(theSchoolId);
return "redirect:/school/list";
}
删除方法 SchoolDAOImpl:
@Override
public void deleteSchool(int theSchoolId) {
Session currentSession=sessionFactory.getCurrentSession();
Query theQuery=currentSession.createQuery("delete from School where id=:schoolID");
theQuery.setParameter("schoolID", theSchoolId);
theQuery.executeUpdate();
}
实际上我现在的问题是我试图删除一所学校,theSchool 至少有 1 名学生,因为我无法删除一所学校。为此,我首先需要在此示例中删除孩子,孩子是删除父母(学校)后的学生。 但我认为我的情况不适用于此。请帮助我该怎么办?
【问题讨论】:
-
“但我认为我的方案不适用于此”。这是什么意思?
-
是的,我的意思是我无法联系到 SchoolDAOImpl 班级的学生。这就是为什么当我尝试删除一所学校时,我无法联系到孩子(学生)。
-
@franiis 我解决了我的问题,我的朋友感谢您的帮助
标签: mysql spring-mvc jpa