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
  • 70,783
  • 26
  • 162
  • 317
Prateek Narendra
  • 1,736
  • 2
  • 30
  • 59
  • 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,546
  • 18
  • 22