1

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

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Prateek Narendra
  • 1,837
  • 5
  • 38
  • 67
  • 1
    Possible duplicate of [How to generate Custom Id using hibernate while it must be primary key of table](https://stackoverflow.com/questions/31158509/how-to-generate-custom-id-using-hibernate-while-it-must-be-primary-key-of-table) – Ubercool Apr 23 '18 at 12:18

1 Answers1

3

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

veljkost
  • 1,748
  • 21
  • 25