简体   繁体   中英

Hibernate + MySQL - How can I get not guessable generated ID?

How can I get entity ID (primary key) to be hard to guess?

Ideal would be 8 or 16 digit random unique number or String.

I tried UUID but it fails with my H2 tests because of reported bug ( https://github.com/h2database/h2database/issues/345 ).

Or if it's hard with ID... how can I get another column to be auto generated with random unique number while creating ?

I need random, hard to guess, unique ID per user for external API.

Thanks for any suggestions. :)

You can assign value to another column using @PrePersist annotation. Something like:

public class MyClass  {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    protected T id;

    @Column
    protected String clientKey;

    @PrePersist
    public void ensureClientKeyGenerated() {
          this.clientKey = UUID.randomUUID();  
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM