UUID stands for Universally Unique ID. A UUID is known in the Microsoft world as as a GUID.
What does a UUID look like?
The UUID is not a string, but a 128-bit value. The UUID is a hexadecimal value like
|
1 |
4536ca53-bcad-4552-977f-16945fee13e1 |
How to generate a UUID in Java?
The “java.util.UUID” class that represents an immutable universally unique identifier (UUID).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.UUID; import javax.inject.Named; import org.springframework.transaction.annotation.Transactional; import com.myapp.UniqueIdentifierGeneratorService; @Named @Transactional public class UniqueIdentifierGeneratorServiceImpl implements UniqueIdentifierGeneratorService { @Override public String generateUid() { final String uuidString = UUID.randomUUID().toString(); LOG.debug("Generated UUID: {}", uuidString); return uuidString; } } |
What are the practical use cases for UUID?
- As a row identity in a database table. i.e. as a primary key. The benefit is that it will be unique across every table, every database, and every server. You can generate IDs anywhere. The disadvantage is that it is 4 times larger than the traditional 4-byte index value. UUIDs may not index well and could degrade database performance.
- UUID is a natural fit for many development scenarios where you need to generate primary keys outside the database.
- Many data replication scenarios require UUID columns. Another option is to let the database generate a sequence key for internal relationships, and use a UUID as a unique secondary key.
- It can be used as an audit tracking id in web service calls.
- It can also be used as a message correlation id.
- Temporary file names.
- Transaction IDs.
- Unique identifiers for website users/visitors.
Generating UUID in Java based on host name & timestamp
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.net.InetAddress; import java.net.UnknownHostException; import java.util.UUID; public final class UuidGenerator { private static String HOST_IP; static { try { HOST_IP = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { HOST_IP = "127.0.0.1"; //localhost } } // can't instantiate from outside private UuidGenerator() {} /** * Generates a {@link UUID} from the current Host IP Address and Epoch Time. * @return the generated {@link UUID}. */ public static UUID fromHostAndCurrentTime() { String currentTime = Long.toString(System.nanoTime()); byte[] genBytes = (HOST_IP + currentTime).getBytes(); return UUID.nameUUIDFromBytes(genBytes); } } |
You can use it as
|
1 2 3 |
UuidGenerator.fromHostAndCurrentTime().toString(); |