Last active
July 14, 2024 12:38
-
-
Save jeffjohnson9046/c663dd22bbe6bb0b3f5e to your computer and use it in GitHub Desktop.
Convert UUID to byte array and vice versa. Useful for when UUIDs are stored in MySQL tables as VARBINARY(16)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer; | |
import java.util.UUID; | |
public class UuidAdapter { | |
public static byte[] getBytesFromUUID(UUID uuid) { | |
ByteBuffer bb = ByteBuffer.wrap(new byte[16]); | |
bb.putLong(uuid.getMostSignificantBits()); | |
bb.putLong(uuid.getLeastSignificantBits()); | |
return bb.array(); | |
} | |
public static UUID getUUIDFromBytes(byte[] bytes) { | |
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); | |
Long high = byteBuffer.getLong(); | |
Long low = byteBuffer.getLong(); | |
return new UUID(high, low); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import junit.framework.Assert; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.springframework.test.context.ContextConfiguration; | |
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | |
import org.springframework.test.context.transaction.TransactionConfiguration; | |
import tds.student.performance.dao.utils.UuidAdapter; | |
import java.util.UUID; | |
@RunWith(SpringJUnit4ClassRunner.class) | |
@ContextConfiguration("/your-test-context.xml") | |
@TransactionConfiguration | |
public class UuidAdapterTest { | |
@Test | |
public void should_Get_16_Bytes_From_a_UUID() { | |
UUID uuid = UUID.randomUUID(); | |
byte[] result = UuidAdapter.getBytesFromUUID(uuid); | |
Assert.assertEquals("Expected result to be a byte array w/16 elements.", 16, result.length); | |
} | |
@Test | |
public void should_Reconstruct_Same_UUID_From_Byte_Array() { | |
UUID uuid = UUID.randomUUID(); | |
byte[] bytes = UuidAdapter.getBytesFromUUID(uuid); | |
UUID reconstructedUuid = UuidAdapter.getUUIDFromBytes(bytes); | |
Assert.assertEquals(uuid, reconstructedUuid); | |
} | |
@Test | |
public void should_Not_Generate_the_Same_UUID_From_Bytes() { | |
UUID uuid = UUID.fromString("9f881758-0b4a-4eaa-b59f-b6dea0934223"); | |
byte[] result = UuidAdapter.getBytesFromUUID(uuid); | |
UUID newUuid = UUID.nameUUIDFromBytes(result); | |
Assert.assertFalse(uuid.equals(newUuid)); | |
} | |
} |
Is this working for UUID version 4? The last Test failes for me.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, this is so useful!.