0

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

1
  • 6 digits and uniqueness is not a good match. How do you want to ensure that without knowing the previous random generated numbers ? You cannot. I think that you should rework on your requirement. Commented Jun 11, 2019 at 15:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, it solves my problem, but it also limits me to have only 10 records. I need to be able to use all the numbers from [10^5, 10^6] set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.