Cannot delete or update a parent row ConstraintViolationException

徘徊边缘 提交于 2019-12-02 08:46:13

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

Make the following change.

//User class
@ManyToMany(cascade = {CascadeType.MERGE,CascadeType.REMOVE}, fetch = FetchType.EAGER)
...
private List<Phone> phones;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!