Created
August 18, 2011 09:19
-
-
Save lifecoder/1153724 to your computer and use it in GitHub Desktop.
UniqueId (UUID) embedded primary key in JPA 2 (Hibernate) for MySQL
This file contains hidden or 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.io.Serializable; | |
import java.nio.ByteBuffer; | |
import java.util.Arrays; | |
import java.util.UUID; | |
import javax.persistence.Access; | |
import javax.persistence.AccessType; | |
import javax.persistence.Column; | |
import javax.persistence.Embeddable; | |
@Embeddable | |
@Access(AccessType.FIELD) | |
public class UniqueId implements Serializable { | |
private static final long serialVersionUID = 4458438725376203754L; | |
@Column(columnDefinition="BINARY(16)", length=16, updatable=false, nullable=false) | |
private byte[] id; | |
public UniqueId() {} | |
public UniqueId(byte[] id) { | |
this.id = id; | |
} | |
public UniqueId(String id) { | |
this(toByteArray(UUID.fromString(id))); | |
} | |
@Override | |
public String toString() { | |
return toUUID(id).toString(); | |
} | |
public static UniqueId fromString(String s) { | |
return fromUUID(UUID.fromString(s)); | |
} | |
public static UniqueId fromUUID(UUID uuid) { | |
return new UniqueId(toByteArray(uuid)); | |
} | |
private static byte[] toByteArray(UUID uuid) { | |
ByteBuffer bb = ByteBuffer.wrap(new byte[16]); | |
bb.putLong(uuid.getMostSignificantBits()); // order is important here! | |
bb.putLong(uuid.getLeastSignificantBits()); | |
return bb.array(); | |
} | |
private static UUID toUUID(byte[] byteArray) { | |
long msb = 0; | |
long lsb = 0; | |
for (int i = 0; i < 8; i++) | |
msb = (msb << 8) | (byteArray[i] & 0xff); | |
for (int i = 8; i < 16; i++) | |
lsb = (lsb << 8) | (byteArray[i] & 0xff); | |
UUID result = new UUID(msb, lsb); | |
return result; | |
} | |
@Override | |
public int hashCode() { | |
final int prime = 31; | |
int result = 1; | |
result = prime * result + Arrays.hashCode(id); | |
return result; | |
} | |
@Override | |
public boolean equals(Object obj) { | |
if (this == obj) | |
return true; | |
if (obj == null) | |
return false; | |
if (getClass() != obj.getClass()) | |
return false; | |
UniqueId other = (UniqueId) obj; | |
if (!Arrays.equals(id, other.id)) | |
return false; | |
return true; | |
} | |
public static UniqueId generate() { | |
return fromUUID(UUID.randomUUID()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lifesaver! Used this for general byte[] primary keys with a reordered UUID component