1

I need a unique alphanumeric code for my entity.

It is not id. There is also id. But also, this code field is unique.

It will be like this

"BS" + 6 alphanumeric chars 

6 alphanumeric.

"BS" is default string. So , all of them will have "BS" in the start

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", updatable = false, nullable = false)
private Long id;

I am using spring boot. With hibernate, i can do such things but i need to make the size 8 or 6+2.

Also my sql has @Generator but i could not manage to do

And each time, i dont want to get from db, increment and save. I think this is not good way?

What can i do? A custom generator?

I looked for this also

https://stackoverflow.com/a/47934704/10309977

but could not a way to see to do

It will be around 1000 generations. So yearly aroudn 1-10 millions.

vegan
  • 117
  • 1
  • 11

1 Answers1

1

A custom generator implementing the logic you need seems to be the best way to generate your unique alphanumeric `code`.

The "problem" with GUID/UUID is that they have a fixed length (longer than you need), you can still get a sub string but you might have a pattern on how the value is generated.

In my experience, I always have generated unique random code values based on a pattern that can be interpreted and retrieve information from it. This is my approach. You have a 62 chars set to work with 26 lowercase letters 26 uppercase letters and 10 numbers.

If your `code` should end with `"-" +2 numbers` you have to generate the 5 chars string then concatenate your 2 numbers.

Also you might need to make your `code` longer than 8 chars

  • 1
    But it will be 10000 new object creations per day. So, in a minute maybe 1000. It cant be unique maybe. – vegan Nov 10 '18 at 21:34
  • That's why you should consider increasing the number of characters of your `code`, but still if your algorithm of how the `code` is generated is solid and well thought it can be unique. You can calculate how many `codes` you can ideally generate with the set you have. – Artion Hasani Nov 12 '18 at 08:43
  • How can i check if it exists while saving, with exception? – vegan Nov 12 '18 at 08:45
  • You should set the property of unique=true to the code column in your entity. It will throw an exception if the constraint isn't fulfilled – Artion Hasani Nov 12 '18 at 08:51
  • But i should again try to save that entity if throw exception. – vegan Nov 12 '18 at 08:54