I created a new application and I am thinking where is the best place to generate a UUID.
- Generate a UUID in application level and persist it
- Generate a UUID in Database level
I have a feeling that is a better approach to generate the UUID in Database level.
What do you think and why?
Many thanks in advance
-
3One of the reasons why you might want to use a UUID is because you want to generate it in the application. Other kinds of primary keys, like consecutive integers, cannot be generated in the application without an extra round trip to the database, making generating them in the database a more favorable approach.Robert Harvey– Robert Harvey2018年06月06日 15:00:39 +00:00Commented Jun 6, 2018 at 15:00
-
1Beyond that, there are several other pros and cons. Which approach is "better" for you depends on what your specific requirements are.Robert Harvey– Robert Harvey2018年06月06日 15:01:33 +00:00Commented Jun 6, 2018 at 15:01
2 Answers 2
You may want to go with "both".
Generating the UUIDs in the application usually makes it easier to run tests as mocking DB logic can be quite fragile.
On the other side of things, if you're developing and need to quickly populate fake data, it's easiest if the UUID can be generated as part of a simple insert statement.
TL;DR: it depends on the context
For most applications IDs should be generated in the DB as this will prevent duplicates if you have multiple client instances, for example load balanced web servers. There are database systems which have different consistency models from SQL RDBMSs which can have the same problem but then you are making an active choice to use an inconsistent DB.
-
4Note that this doesn't really apply for UUIDs, as the entire point is that they are "unique" purely through probability.Turksarama– Turksarama2018年07月09日 01:34:48 +00:00Commented Jul 9, 2018 at 1:34