无法删除或更新父行ConstraintViolationException
我有2个对象实体(用户和电话),它们应该具有多对多关系。
//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;
//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;
现在,我在USER表中添加了ID为1和2的2个用户。然后,我添加一个ID为1的电话,并将它们映射到两个用户ID(1&2)。
我的USER_PHONE表如下所示:
Select * from USER_PHONE;+----------+---------+
| phone_id | user_id |
+----------+---------+
| 1 | 1 |
| 1 | 2 |
+----------+---------+
现在,我希望删除ID为2的用户。尝试执行此操作时,出现错误
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`))
我的删除脚本:
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;
}
知道我哪里出错了吗?非常感谢 :)
回答:
尝试使用entityManager.createNativeQuery()
。您不能使用,createQuery()
因为该表应该作为实体存在于Java代码中。另外,您需要使用确切的SQL格式。
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;
}`
首先从USER_PHONE
(使用createNativeQuery()
)删除行,然后从User
(使用createQuery()
)删除行
以上是 无法删除或更新父行ConstraintViolationException 的全部内容, 来源链接: utcz.com/qa/417407.html