如何删除休眠中具有外键的行?

时间:2017-12-10 19:17:45

标签: mysql spring hibernate

我有两个名为usersroles的表。用户只能有一个角色。 我想要做的是按ID删除用户。但我得到以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`supermarket`.`users`, CONSTRAINT `FKcogjq1smjy03v5s2wfegritx6` FOREIGN KEY (`role_id`) REFERENCES `Roles` (`role_id`))

据我所知,我删除了具有外键的用户中的行。但我无法弄清楚,如何删除roles表中的行,然后才删除users表中的记录。如何实现这个只做一个查询?

以下是我的课程:

@Entity
public class Users {
private int userId;
private String login;
private String password;
private Roles roles;

public Users(String login, String password, Roles roles) {
    this.login = login;
    this.password = password;
    this.roles = roles;
}

public Users() {
}


@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "role_id")
public Roles getRoles() {
    return roles;
}

public void setRoles(Roles roles) {
    this.roles = roles;
}

 //getters and setters 

角色:

@Entity
public class Roles {
private int roleId;
private String roleName;

@Id
@Column(name = "role_id", nullable = false)
public int getRoleId() {
    return roleId;
}

public void setRoleId(int roleId) {
    this.roleId = roleId;
}

@Basic
@Column(name = "role_name", nullable = true, length = 14)
public String getRoleName() {
    return roleName;
}

public void setRoleName(String roleName) {
    this.roleName = roleName;
}

}

以下是删除方式:

 public void deleteCasher(int id) {

    Session session = sessionFactory.openSession();
    Query query = session.createQuery("from Users where userId=:id")
            .setParameter("id", id);

    Users user = (Users) query.uniqueResult();

    session.beginTransaction();
    session.delete(user);
    session.getTransaction().commit();
    session.close();


}

那么,我做错了什么?如何删除用户,同时删除role,进行一次查询?

2 个答案:

答案 0 :(得分:2)

如果您希望该行为是永久,则表示每次删除用户时,您都可以在创建表后更改外键操作。这直接进入MySQL,跟随this answer

将约束从ON DELETE RESTRICT更改为ON DELETE CASCADE

ALTER TABLE `users` DROP FOREIGN KEY `FKcogjq1smjy03v5s2wfegritx6`; 

ALTER TABLE `users` ADD CONSTRAINT `FKcogjq1smjy03v5s2wfegritx6`
  FOREIGN KEY (`role_id`) REFERENCES `Roles` (`role_id`)
  ON DELETE CASCADE; 

答案 1 :(得分:1)

可能的原因 -

1--在创建用户时,如果要在角色表中创建具有相应用户标识的角色

2--如果你在其他表中使用userid作为FOREIGN KEY ....