'How to create a unique number in java before sending an SQL query [duplicate]

I am making an app in java that sends SQL queries. The user can propose a room that others can book. To propose a room, the user has to fill a form. When the user fills the form and presses on the validate button, the app create an SQL query that insert the inputted information in a table proposedRoom.

However each proposed room in my table has a primary key, proposedRoomId which is an int. I am having trouble creating that primary key in Java before sending the Query to insert the room in the table.

What I tried to do is using the date to generate the corresponding integer, but if two people happen to propose a room at the same time it will cause error. I thought about hashing and changing the type of the key to String but this seems complicated and may reduce my app performance.



Solution 1:[1]

If you have access to the DBMS, you can alter the definition of proposedRoomId column and add AUTO_INCREMENT to it. Then you need not worry about that.

I've no idea how things work with JDBC but there must be some way to get LAST_INSERT_ID too.

Solution 2:[2]

You can take the following approaches:

  1. If you can convert proposedRoomId to String, try using UUID.
  2. Try to create hash by taking a combination of RoomID and UserID.
  3. Try to create hash by taking combination of timestamp and RoomID.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hemanth788
Solution 2 Prakul