How to get an element id that has just been inserted - JAVA

Asked

Viewed 945 times

1

How do I catch one id of an element that has just been inserted into Database in Java? Something like: mysql_insert_id() in the PHP.

  • 1

    You are using JDBC with PreparedStatement and ResultSet? Or is using some other API?

  • 1

    What is the database?

  • If it is with Mysql (I don’t know if all banks are like this) has the answer on the site itself: How to return the ID of a record right after it is inserted?

  • If you don’t find a better way, in the latter case you can do the Insert with a transaction and a select id from table order by id desc limit 1;

  • Thanks, guys, I discovered that Hibernate, through persist or merge, already returns an object filled with the Bank ID. Sorry the delay to post the solution! Thank you all, success!

1 answer

1


Within a transaction, right after inserting into the bank and before carrying out the commit, you can do SELECT id FROM tabela WHERE ROWNUM = 1 ORDER BY id DESC (SQL for Oracle). This query will return the last id inserted.

SQL may vary depending on your database, but that’s the idea.

  • 1

    Thanks, guys, I discovered that Hibernate, through persist or merge, already returns an object filled with the Bank ID. Sorry the delay to post the solution! Thank you all, success!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.