繁体   English   中英

MySQL事务性删除和Java

[英]MySQL Transactional delete and Java

我有这样的表:

Table A:  
`id | name`

Table B:  
`id | A_id | ....`  

A_id is a foreign key to Table A, the Engine is InnoDB

这是失败的代码:

    String[] cleanupQueries = new String[] { "DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name = 'test')",
                                            "DELETE FROM A WHERE name = 'test'" };

    Connection connection;
    try {
        connection = DriverManager.getConnection(getConnectionString());
        connection.setAutoCommit(false);
    } catch (SQLException e) {
        throw new RuntimeException("Error establishing a database connection!");
    }

    try {
        for(String cleanupQuery : cleanupQueries) {
            PreparedStatement statement = connection.prepareStatement(cleanupQuery);
            statement.executeUpdate(); //FAILS WHEN EXECUTING THE SECOND QUERY
        }
    } catch(SQLException e) {
        throw new RuntimeException("Error while executing the queries in the transactional context!");
    }

    try {
        connection.commit();
    } catch (SQLException e) {
        rollback(connection);
        throw new RuntimeException("Error while comitting!");
    }

我得到的异常是: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails ('DATABASE/TABLE', CONSTRAINT 'FK_B_A' FOREIGN KEY ('FK_A') REFERENCES 'A' ('ID') ON DEL)

该数据库不允许我删除A,而B仍然剩余,但是第一个查询删除了所有B。 我只想删除它们仅引用的所有B和A。

我不想更改表以进行级联删除。 我应该怎么做才能使代码正常工作?

错误原因是

外键已引用表A id,因此,如果要删除F_Key,首先应删除该外键的Child引用值,然后才可以删除父键。

如果错了,请纠正我。

删除外键约束时,只需添加级联为true。删除原始父项时,子表项会自动删除。

尝试:

"DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name IN 'test')"

由于在同一事务中删除了子行,因此删除的行仍然可见,因此无法删除父行。 这可能是由于连接上的事务隔离设置所致。 我会尝试不同的级别,看看哪个允许它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM