Java – Oracle database SELECT… FOR UPDATE with autocommit on

javajdbcoracleoracle11g

I'm running this query against an Oracle database (11g). The connection has the default value for autocommit which is 'true'.

Connection con = driver.connect(url, properties);
String query = "SELECT EMPID, NAME FROM EMPLOYEE FOR UPDATE";

Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet resultSet = statement.executeQuery(query);

SELECT… FOR UPDATE states that it "lock the selected rows so that other users cannot lock or update the rows until you end your transaction." With autocommit on it should be immediately after the query is executed. But the lock is present till the connection is closed.

(I checked this by running query select * FROM DBA_DML_LOCKS WHERE NAME = 'EMPLOYEE'; on sqlplus.)

Is this a bug or can somebody please explain why?
Thank you in advance.

Best Answer

As said in documentation:

the default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed

Another documentation:

Enabling auto-commit may be more convenient, but gives you less control. For example, you have no option to roll back changes. In addition, some SQLJ or JDBC features are incompatible with auto-commit mode. For example, you must disable the auto-commit flag for update batching or SELECT FOR UPDATE syntax to work properly.

So for this query type you should use manual commit

Related Topic