简体   繁体   中英

MySQL Transactional delete and Java

I've got tables like this:

Table A:  
`id | name`

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

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

This is the code that fails:

    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!");
    }

The Exception i get is: 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)

The database doesn't let me delete A while there are still B's left, but the first query deleted all B's. I want to delete all B's and the A they reference only completely.

I don't want to change the Tables to have cascading deletes. What shall i do to get the code working?

Cause for error is

The Foreign Key has referenced to the table A id so if you would like to delete the F_Key , first you should delete the Child references values of that foreign keys then only its possible to delete the parent.

Correct me if 'm wrong..

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

尝试:

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

Since the child rows are deleted in the same transaction, the deleted rows are still visible and thus the parent rows could not be deleted. This may be because of the transaction isolation setting on the connection. I would try different levels and see which one allows it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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