禁用外键检查后无法删除或更新父行

时间:2018-01-10 07:09:10

标签: java mysql jpa

我想更新表中的键,这个键在其他表中是FK。

em.createNativeQuery("SET FOREIGN_KEY_CHECKS=0").getResultList().

em.createNativeQuery("update user set name = ?1  where name = ?2").executeUpdate();

query.setParameter(1, "aa");
query.setParameter(2, "bb");

但即使我禁用了外键检查,我也会收到异常。

  

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   无法删除或更新父行:外键约束失败   (test_import_1assessment_user,CONSTRAINT   FK32kg3rlqty5i2i729a22icn7q FOREIGN KEY(user_name)参考   username))

1 个答案:

答案 0 :(得分:1)

如何将两个查询用作以下查询:

StringBuilder query = new StringBuilder();
query.append("BEGIN ")
    .append("SET FOREIGN_KEY_CHECKS = 0 ;")//query to disable foreign key checks
    .append("UPDATE user SET name = ?1 WHERE name = ?2;")//The update query
    .append("SET FOREIGN_KEY_CHECKS = 1")//when you finish enable the check 
    .append(" END;");

Query q = em.createNativeQuery(query.toString());
query.setParameter(1, "aa");
query.setParameter(2, "bb");
q.executeUpdate();// Note executeUpdate() should be used AFTER you set the parameters 

第二个选项:

em.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0").executeUpdate();

Query q = em.createNativeQuery("UPDATE user SET name = ?1 WHERE name = ?2;");
query.setParameter(1, "aa");
query.setParameter(2, "bb");
q.executeUpdate();

em.createNativeQuery("SET FOREIGN_KEY_CHECKS = 1").executeUpdate();