Cannot delete or update a parent row ConstraintViolationException

南笙酒味 提交于 2019-12-02 21:09:26

问题


I have 2 object entities (User and Phone) and they are supposed to have many-to-many relations.

User.java

//all columns

@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
    @JoinTable(name = "USER_PHONE",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "phone_id", referencedColumnName = "id"))
    private List<Phone> phones;

Phone.java

//all columns
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
    @JoinTable(name = "USER_PHONE",
            joinColumns = @JoinColumn(name = "phone_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
    private List<User> userList;

Now, I add 2 users with IDs 1 and 2 in my USER table. Then, I add a single phone with id 1 and map them to both the user IDs(1&2) .

My USER_PHONE table looks as below:

Select * from USER_PHONE;
+----------+---------+
| phone_id | user_id |
+----------+---------+
|        1 |       1 |
|        1 |       2 |
+----------+---------+

Now, I wish to remove a user with ID 2. When I try to do this, I get an error

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`dbname`.`USER_PHONE`, CONSTRAINT `FKC6A847DAFA96A429` FOREIGN KEY (`user_id`) REFERENCES `USER` (`ID`))

My delete script:

  String query = "DELETE User where id=?1";
        try{
            Query q = entityManager.createQuery(query);
            q.setParameter(1,id);
            q.executeUpdate();
            System.out.println(System.currentTimeMillis() + " DELETE: userId " + id + " ==> deleted");
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }

Any idea where am I going wrong ? Thanks a lot :)


回答1:


Try using entityManager.createNativeQuery(). You cannot use createQuery() because the table should be present as an entity in your Java code. Also, you need to use the exact SQL format.

String query = "DELETE FROM USER_PHONE WHERE user_id=?1";

    try{
        Query q = entityManager.createNativeQuery(query);
        q.setParameter(1,id);
        q.executeUpdate();
        System.out.println(System.currentTimeMillis() + " DELETE User_Phone: userId " + id + " ==> deleted");
    } catch(Exception e){
        e.printStackTrace();
        return false;
    }`

First delete the row from USER_PHONE (using createNativeQuery()), and then from User (using createQuery())




回答2:


Make the following change.

//User class
@ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REMOVE}, fetch = FetchType.EAGER)
...
private List<Phone> phones;


来源:https://stackoverflow.com/questions/40641181/cannot-delete-or-update-a-parent-row-constraintviolationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!