Matt Felzani
Matt Felzani

Reputation: 795

Possible to preserve UUID case when created from String?

From this code:

String in = "E5D552ED-03AB-4AFA-B484-0D2C4FD64432";
UUID uuid = UUID.fromString(in);
String out = uuid.toString();

I get this output:

>  in: E5D552ED-03AB-4AFA-B484-0D2C4FD64432
> out: e5d552ed-03ab-4afa-b484-0d2c4fd64432

The issue is we use the String as the primary key on a row we insert into the DB before we create the UUID, and once it goes into the UUID we have an issue with getting back to that initial row since the DBMS is case-sensitive and we only have the UUID once it's created.

And I should have noted the input case is not consistently all upper or all lower. We work with a lot of vendors ... some send all caps, some all lower.

I'd rather not have to store an additional boolean on the side.

Upvotes: 1

Views: 2730

Answers (4)

Joseph Fitzgerald
Joseph Fitzgerald

Reputation: 311

You're going to get much better performance out of your database if you store the UUID as BINARY(16), which is 16 bytes, rather than CHAR(36), which is 36 bytes (if you're using a character set that uses a single byte per character)

This is a similar problem to storing number is a varchar column. You can do it, but it's rarely the right way to go.

Upvotes: 1

dolmen
dolmen

Reputation: 8696

Just make the database column case-insensitive. For example with MySQL, use a collation ending with _ci : UUID CHAR(36) CHARSET ascii COLLATE ascii_general_ci.

Upvotes: 1

Markus
Markus

Reputation: 2143

Taken from RFC4122 (and also described here) "The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input."

Which in consequence means that your in & out is the same UUID. But the String representations are different.

So there are two options for you to do:

  1. Store it consistently as lower case String (either String.toLowerCase() or using database technology e.g. LCASE/LOWER to store it persistently)
  2. Second option would be to store the UUID in an optimized way (as a number) see here: how to store UUID as number

Be aware that option 2 is more complex, especially if you want to restore the String representation. And Option 1 may need cleanup of your DB if you have unique constraints or want to prevent data loss.

Upvotes: 3

ferahgo
ferahgo

Reputation: 408

You could extend UUID and then override toString to always give the representation of the string in all capitals.

@Override
public String toString() {
    return super.toString().toUpperCase();
}

Upvotes: 3

Related Questions