Cannot delete or update a parent row ConstraintViolationException

后端 未结 2 782
礼貌的吻别
礼貌的吻别 2021-01-26 04:13

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

User.java

//all columns

@ManyToMany(ca         


        
相关标签:
2条回答
  • 2021-01-26 04:27

    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())

    0 讨论(0)
  • 2021-01-26 04:38

    Make the following change.

    //User class
    @ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REMOVE}, fetch = FetchType.EAGER)
    ...
    private List<Phone> phones;
    
    0 讨论(0)
提交回复
热议问题