Vadim Fedorenko
Vadim Fedorenko

Reputation: 2571

How to assign random unique value generated by the database to Hibernate POJO's field

The problem is that I need to generate unique value for the one of my POJOs field in Java. I am using Hibernate.

It is pretty simple to solve it using sequence generator, but in my reality I need to make it random every time and I need it to have value between 10^5 and 10^6 — it must be 6 digits number.

So, it is also not a problem to generate it locally in Java service, but what if I have 2 more same services. What if they will generate same number, which break my numbers uniqueness. That's why I need that number to be generated by database.

Please, advice me best approach to achieve this. What strategy I need to follow. Thanks

Upvotes: 0

Views: 223

Answers (1)

steven35
steven35

Reputation: 4017

There is no need to do this at ORM level. Just let the database engine auto increment it.

You can set the field to be unique and auto increment from 100,000 AUTO_INCREMENT = 100000; when you are creating the table.

Your numbers will then guaranteed to be unique.

You could also do this manually at service level if you put both checking for the highest existing number and the insert in the same transaction.

You could also do it via a trigger.

Upvotes: 1

Related Questions