问题
I am developing an application using Java and I have an Oracle database. To store data I am using JDBC. In Oracle database, there is nothing like a Auto Increment. So I have used triggers to get the lastest primary key.
Currently the application has been implemented and I get the saved primary key back. This happens when the connection.setAutoCommit(true) is set. What I would like to know if I set the connection.setAutoCommit(false) is it possible to get the primary key?
The reason why I ask this is because I am facing some concurrency issue with multiple threads where one thread saves the data and and another thread can pick up the saved record. I don't want this to happen. I want the code to be sequentially completed before the other thread views the data. So, I tried to investigate JDBC row lock but nothing like this exists.
This primary key is required for an input into another method within the same Thread.
回答1:
The correct way to retrieve your primary key is to use the getGeneratedKeys facility (which can be activated by using the Statement.RETURN_GENERATED_KEYS value with one of the Statement.execute* or Connection.prepareStatement methods.
In most databases this can be used to retrieve the primary key directly. In the case of Oracle however this will allow you to obtain the ROWID, this ROWID can be used to query the table for the inserted row and obtain the primary key.
For example:
stmt.executeUpdate("INSERT INTO theTable(column1) VALUES ('a')",
Statement.RETURN_GENERATED_KEYS);
ResultSet keys = stmt.getGeneratedKeys();
int primaryKey = -1;
if (keys.next()) {
try (PreparedStatement keyStatement =
connection.prepareStatement("SELECT ID FROM theTable WHERE ROWID = ?")) {
keyStatement.setRowId(keys.getRowId(1));
try (ResultSet rs = keyStatement.executeQuery()) {
primaryKey = rs.getInt(1);
}
}
}
回答2:
In addition to the solution provided by @Mark Rotteveel, you can specify the exact columns you want values returned from by using Connection.prepareStatement(String, String[]). In this case, if you provide the column name for you primary key, that value will be in the ResultSet returned from Statement.getGeneratedKeys.
Another option is to get the value for the primary key from the sequence and insert as part of your insert statement rather than using a trigger:
select mysequence.nextval from dual
来源:https://stackoverflow.com/questions/24136223/java-jdbc-primary-key-oracle-database