Skip to content

Instantly share code, notes, and snippets.

@lifecoder
Created August 18, 2011 09:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lifecoder/1153724 to your computer and use it in GitHub Desktop.
Save lifecoder/1153724 to your computer and use it in GitHub Desktop.
UniqueId (UUID) embedded primary key in JPA 2 (Hibernate) for MySQL
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());
}
}
@vijay-daniel
Copy link

Lifesaver! Used this for general byte[] primary keys with a reordered UUID component

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment