Using a UUID as a Database Primary Key, Java type

2019-07-11 20:47发布

Are there any issues with using a byte[] as a primary key in a JPA Entity?

I want to use a UUID as my primary key, but stored as a string I feel it will be too large.

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;

    }

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.

3条回答
爷的心禁止访问
2楼-- · 2019-07-11 21:15

I'll concur with an earlier respondent that storing the keys as bytes will make the very difficult to query by hand when doing problem diagnosis. Using a char(x) or varchar(x) field will not consume significantly more space and will be much easier for support staff to read.

查看更多
Animai°情兽
3楼-- · 2019-07-11 21:21

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.

查看更多
一夜七次
4楼-- · 2019-07-11 21:23

I don't think there are going to be issues with this other than a little bit of performance penalty for having a Primary Key larger than a usual 4 bytes (int) one.

Why do you need a UUID as your primary key? Why can't you just use a surrogated integer key with a autoincrement?

查看更多
登录 后发表回答