簡體   English   中英

無法刪除或更新父行:Spring Boot JPA 中的外鍵約束失敗

[英]Cannot delete or update a parent row: a foreign key constraint fails in Spring Boot JPA

我正在實現 Delete 方法,從用戶那里我得到需要從 User 表中刪除的 userId。 但是這個user表是通過OneToMany映射映射到UserRole表的。 因此,當我嘗試刪除 userId 時,因為 userId 作為外鍵存在於 UserRole 中,我無法刪除它。 得到

java.sql.SQLIntegrityConstraintViolationException:不能刪除或更新父行,外鍵約束失敗( examuser_role ,約束FKj345gk1bovqvfame88rcx7yyx外鍵( user_id )參考usersid ))

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    private String username;
    private String password;
    private String email;
    private String phone;
    private boolean enabled;
    private String profile;
    
    
    //user has many role
    @OneToMany(cascade = CascadeType.ALL,orphanRemoval = true ,fetch = FetchType.EAGER,mappedBy = "user")
    @JsonIgnore
    private Set<UserRole> userRoles = new HashSet<>();
}

 @Entity
    public class UserRole {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long userRoleId;
        
        //User
        @ManyToOne(fetch = FetchType.EAGER)
        private User user;
        
        @ManyToOne
        private Role role;
}

首先,您需要從 UserRole 表中刪除該用戶的條目,然后才允許您由於引用而從用戶表中刪除

首先檢查是否有約束,如果有則刪除相關行然后你可以刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM