Prateek Narendra
Prateek Narendra

Reputation: 1937

String ID Primary Key generator in JPA/Hibernate

I know that we can generate a random UUID -

@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String myId;

But UUID is a String if size 32. How can i generate a random alphanumeric string of size 6 and store as ID?

I want to store this in MongoDB

Upvotes: 1

Views: 2084

Answers (1)

veljkost
veljkost

Reputation: 1932

You will have to create a custom ID generator by implementing hibernate's IdentifierGenerator.

public class SomeCustomGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate() {...}
}

And then use it:

@Id
@GeneratedValue(generator = "cust-generator")
@GenericGenerator(name = "cust-generator", strategy = "com...generator.SomeCustomGenerator")
private String myId;

Take a look at the example

Upvotes: 3

Related Questions