使用UUID作为数据库主键,Java类型是一个字节[] [英] Using a UUID as a Database Primary Key, Java type is a byte[]
问题描述
在JPA实体中使用byte []作为主键是否存在任何问题?
Are there any issues with using a byte[] as a primary key in a JPA Entity?
我想使用UUID作为主键,但是存储为字符串,我觉得它太大了.
I want to use a UUID as my primary key, but stored as a string I feel it will be too large.
我当时正在考虑做这样的事情来将ID存储为字节[]并将其设置为我实体的ID:
I was thinking of doing something like this to store the ID as a byte[] and set it as my Entity's ID:
public static byte[] byteArray(UUID uuid) {
long lsb = uuid.getLeastSignificantBits();
long msb = uuid.getMostSignificantBits();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
dos.writeLong(lsb);
dos.writeLong(msb);
dos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = bos.toByteArray();
// System.out.println("Byte Array Length "+data.length);
return data;
}
在数据库中为此设置索引会遇到麻烦吗?我同时使用Postgres和HSQL.我正在使用Hibernate作为我的JPA提供程序.
Will I have any trouble putting indexes on this in the DB? I am using both Postgres and HSQL. I am using Hibernate as my JPA provider.
推荐答案
请记住,使用SQL客户端的用户在查询byte [] id时会遇到麻烦.这就是为什么数据库ID通常是数字的原因.手写查询要容易得多.
Bear in mind that users using an SQL client will have trouble querying for byte[] ids. That's why db ids are typically numbers; it's much easier to hand-write queries.
这篇关于使用UUID作为数据库主键,Java类型是一个字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!