Reputation: 1205
my java JPA Entity use the following code to generate its UUID
@Entity
public class Myclass {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
String id;
String name;
}
In Oracle and in java as a string, the ID end up being something like this:
2c96cc2a52f9f9a90152fa6549f40008
a 32 hexadecimal character string.
I have to interact with some third party system that needs to save my ID in various places and it has to be the same. Unfortunately, their fields only allow 30-character string (any char, not only hexadecimal).
So I need my uuid to look like a 30-character or less string wherever it appears (in oracle, in java, in that third party system, etc).
What should i do so that the representation of that uuid uses all the alphanumerical characters ('ghi...z' but no weird characters) to be shorter and how to make sure this representation is what is visible in the DB and in the app?
Many Thanks
Upvotes: 0
Views: 1938
Reputation: 1205
Thanks for the help! using base36 does the trick indeed. One more thing is necessary however to make sure the shorter ID is the one that appears in the DB as well:
@PrePersist
public void generateId() {
String uuid_string = UUID.randomUUID().toString().replaceAll("-","");
BigInteger big = new BigInteger(uuid_string, 16);
String same_uuid_shorter_string = big.toString(36);
id = same_uuid_shorter_string ;
}
(also get rid of the original id generator annotations)
Upvotes: 2
Reputation: 77177
If you're willing to deal with some odd-looking keys, encode the UUID in a base higher than 16, such as Base36 (all the letters and digits, can be case-insensitive) or Base64 (usually not URL-safe). If you want something URL-safe that's as compact as possible, you can use my implementation of Flickr-compatible Base58, which has specific helpers for encoding and decoding UUID objects.
Upvotes: 2