How should I use UUID with JavaDB / Derby and JDBC?

I am currently using INT as the primary key type in JavaDB (Apache Derby), but since I am implementing a distributed system, I would like to change the type to java.util.UUID . A few questions about this:

  • What type of data in JavaDB / Derby should be used for UUID? I have seen CHAR(16) FOR BIT DATA , but I know little about it. Is VARCHAR(16) an alternative?

  • How do I use it with JDBC? For instance. in PreparedStatement , how should I set and get the UUID?

  • If later I want to change the database to SQL Server, is there a compatible data type for java.util.UUID?

Just how should I use UUID with JavaDB / Derby and JDBC?

+4
source share
3 answers

UUID is a 128-bit value. The CHAR(16) FOR BIT DATA reflects the fact that bit data is stored in character form for brevity. I don't think VARCHAR(16) will work because it does not have a bit flag. A database would need to be able to convert binary data into character data that deals with encoding, and is risky. More importantly, he would not buy anything. Since the UUID is always 128 bits, you do not get space savings from using VARCHAR over CHAR . So you can also use the intended CHAR(16) FOR BIT DATA .

With JDBC, I think you are using the get / setBytes () method as it deals with small amounts of binary data. (Not positive, I would have to try this)

And I don’t know about the part of SQL Server.

+10
source

If you still want to use the UUID object in your code, you can use fromString to create UUID objects from the database and toString to store them in the database.

+3
source

You can convert the UUID to a string and save it as a VARCHAR. Most UUID string formats look like this: 32 digits separated by hyphens: 00000000-0000-0000-0000-000000000000, so you need VARCHAR (36) or do something like VARCHAR (64) if you want, since it doesn't hurt to have additional "space" available in your VARCHAR - only actual numbers are saved.

Once you convert it to a string, just call Statement.SetString to include it in your INSERT statement.

-4
source

All Articles