BASE64 compression UUID length replace hibernate legacy UUID Generator

Source: Internet
Author: User
Tags base64 rfc

This article comes from http://my.oschina.net/noahxiao/blog/132277, personal storage use

1. Background

When I use Hibernate to do object mapping, I always use the UUID to master the key. Since Hibernate's UUID needs to occupy 32-bit characters, it generally makes people feel more efficient and increase storage usage.

When I looked at the company project, I found a better way to build the UUID, which was to Base64 the UUID data. Feel more meaningful to come out to share with you.

2, traditional Uuida, Java.util.UUID

The UUID in Java uses the RFC 4122 standard, which is represented as 16 binary by standard data (36 characters). such as: F81d4fae-7dec-11d0-a765-00a0c91e6bf6

B, Hibernate UUID

Hibernate defaults to produce a UUID that, compared to the RFC 4122 standard, removes the unused "-" split symbol, so it is shorter (32 characters). such as: F81d4fae7dec11d0a76500a0c91e6bf6

3. UUID in BASE64 format

Since the characters used by the BASE64 encoding include 26 uppercase and lowercase letters, plus 10 digits, and a plus sign "+", a slash "/", altogether 64 characters. So the origin of the Base64 name. Base64 is equivalent to using 64 binary to represent the data, the same length number of bits in the case of more than the 16 binary representation of the content.

Since the UUID standard data is 128-bit in total, we can re-encode the 128-bit Base64.

The UUID of 128-bit is represented as two long data in Java, The Getleastsignificantbits and getmostsignificantbits in Java.util.UUID can be used to obtain two long (64-bit) respectively. Then we can get the uuid we want by Base64 transcoding.

Uuidutils Tool Class

 PackageOrg.noahx.uuid;Importorg.apache.commons.codec.binary.Base64;ImportJava.util.UUID; Public Abstract classUuidutils { Public StaticString uuid () {UUID UUID=Uuid.randomuuid (); returnuuid.tostring (); }      Public StaticString Compresseduuid () {uuid UUID=Uuid.randomuuid (); returncompresseduuid (UUID); }     protected StaticString compresseduuid (uuid uuid) {byte[] Byuuid =New byte[16]; Longleast =uuid.getleastsignificantbits (); Longmost =uuid.getmostsignificantbits (); Long2bytes (most, Byuuid,0); Long2bytes (least, Byuuid,8); String Compressuuid=base64.encodebase64urlsafestring (BYUUID); returnCompressuuid; }     protected Static voidLong2bytes (LongValuebyte[] Bytes,intoffset) {         for(inti = 7; i >-1; i--) {Bytes[offset++] = (byte) ((Value >> 8 * i) & 0xFF); }    }      Public Staticstring Compress (string uuidstring) {uuid uuid=uuid.fromstring (uuidstring); returncompresseduuid (UUID); }      Public Staticstring uncompress (String compresseduuid) {if(Compresseduuid.length ()! = 22) {            Throw NewIllegalArgumentException ("Invalid uuid!"); }        byte[] Byuuid = base64.decodebase64 (compresseduuid + "= ="); Longmost = Bytes2long (byuuid, 0); Longleast = Bytes2long (Byuuid, 8); UUID UUID=NewUUID (most, least); returnuuid.tostring (); }     protected Static LongBytes2long (byte[] Bytes,intoffset) {        LongValue = 0;  for(inti = 7; i >-1; i--) {Value|= (((Long) bytes[offset++]) & 0xFF) << 8 *i; }        returnvalue; }}

By calling the Uuidutils.compresseduuid () method, I can get the UUID string I need (22 characters, 128-bit Base64 only 22 characters). such as: Bwcyzlfgtactz9_juxsnya

10 characters shorter than Hibernate32 characters.

When dealing with Base64, the Apache COMMONS-CODEC Coding Toolkit is used here because it provides a simple encoding conversion method. There are also encodebase64urlsafestring methods that generate BASE64 encoding in a URL-safe manner. The default Base64 contains + and/characters, which will cause confusion if the encoding appears in the URL. The URL security method uses-replace +,_ replace/, and remove the end = =. Ideal for Web direct-pass parameters.

4. Hibernate's UUID generator

The implementation of the ID generator is slightly different (import) because Hibernate4 has made adjustments to the Sessionimplementor package.

A, Hibernate3
 PackageOrg.noahx.uuid;Importorg.hibernate.HibernateException;ImportOrg.hibernate.engine.SessionImplementor;ImportOrg.hibernate.id.IdentifierGenerator;Importjava.io.Serializable; Public classBase64uuidgeneratorImplementsIdentifiergenerator {@Override PublicSerializable Generate (Sessionimplementor session, Object object)throwshibernateexception {returnUuidutils.compresseduuid (); }}
B, Hibernate4
 PackageOrg.noahx.uuid;Importorg.hibernate.HibernateException;ImportOrg.hibernate.engine.spi.SessionImplementor;ImportOrg.hibernate.id.IdentifierGenerator;Importjava.io.Serializable; Public classBase64uuidgeneratorImplementsIdentifiergenerator {@Override PublicSerializable Generate (Sessionimplementor session, Object object)throwshibernateexception {returnUuidutils.compresseduuid (); } }
UUID using BASE64 in the map
@Id     = "Uuidgenerator", strategy = "Org.noahx.uuid.Base64UuidGenerator")    = "Uuidgenerator")    @ Column ("uuid", length =)    private String UUID;

BASE64 compression UUID length replace hibernate legacy UUID Generator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.