2

I am working on a SpringBoot application. The strict requirement I have is to generate server-side a numeric id for an entity and then persist it through the repository. Since each @Service is stateless and so a singleton, is the usage of an AtomicLong a good way to implement it?

Here is my code.

In the service, I have this field

private final AtomicLong currentId = new AtomicLong();

In the service in the called method, I use the repository to persist data in this way:

myEntityRepository.save(MyEntity.builder()
    .id(currentIdNumber.incrementAndGet())
    //.... defining other fields
    .build());

If the code I provided is not enough to answer me, I will happily edit my question according to the comments.

2 Answers2

4

No, that's the wrong way to go. Most applications need to be able to stand up multiple instances of an application for availability, once there is a second instance of your service the ids won't be unique.

Even if this is homework, it's an opportunity to learn how to do this. Picking the wrong way to allocate ids has made huge problems for real world projects so this is a good thing to know.

There's already an easy, normal way to do this. Put a @GeneratedValue annotation on the ID field of the entity, and have the database generate the ID using sequences or setting up the column as an identity, depending on the database, some have identity, some have sequences. See this tutorial https://www.baeldung.com/hibernate-identifiers, or this very detailed one https://jpa-buddy.com/blog/the-ultimate-guide-on-db-generated/ (Spring doesn't do anything with this actually, it's all JPA). The database can make sure these ids will be unique.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
3

UUID

Personally I think that using universally unique identifier (UUID) is a better solution.

They are exactly designed for your situation: Where you need to generate unique identifiers without depending on a central registration authority, and without coordinating between the parties generating them.

Here is a an article about UUID in Java : https://www.baeldung.com/java-uuid

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • I actually have the requirement to use a numeric id (I am going to edit the question). – George Lords of Castle Apr 26 '23 at 10:33
  • 1
    You can generate numeric-only uuids, like this: String lUUID = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16)); Credit : https://stackoverflow.com/questions/8092970/is-there-a-way-to-generate-a-random-uuid-which-consists-only-of-numbers – Bastian Hologne Apr 26 '23 at 12:30