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

19
June 12, 2019, at 08:10 AM

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

Answer 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.

READ ALSO
How to parse a number in a JTextField dynamically

How to parse a number in a JTextField dynamically

I'm trying to dynamic parse a entry in a JtextField, basically if my user type 100000 the TextField woud show 100 000

20
How file manipulations perform during power outage

How file manipulations perform during power outage

Linux machine, Java standalone application

14
How can I make one flowfile the child of a separate pre-existing flowfile?

How can I make one flowfile the child of a separate pre-existing flowfile?

When a flowfile comes into existence from an external source, but knows the uuid of an prior flowfile that it came from, how can I mark the existing flowfile as a parent of this one

51
Open PDF in new tab, saving file gives wrong file name

Open PDF in new tab, saving file gives wrong file name

There is an Angular 6 app having a feature to download pdf filesIt uses REST API from another Spring Boot application to download files

54