Home > Mobile >  Unique ID Generation From DB value with 11 digits using Java causing Unique constraint exception
Unique ID Generation From DB value with 11 digits using Java causing Unique constraint exception

Time:01-05

I have a requirement where we need to generate unqiue block ID which will be 11 characters.

We have below logic to generate it,

public String generateBlockId(){
        boolean alreadyExists = true;
        String newBlockId = "";
        
        while(alreadyExists) {
        
            newBlockId = generateYYDDDSSSSSString();
            
            Allocation allocation = repo.findTopByBlockId(newBlockId);
            if(allocation == null) {
                blockIdAlreadyExists = false;
            }
        }
        
        return newBlockId;
    }
    
    
public String generateYYDDDSSSSSString() {
        String dateString;
        LocalDateTime now = LocalDateTime.now();
        Integer year = now.getYear() % 100;
        Integer day = now.getDayOfYear();
        Integer second = now.toLocalTime().toSecondOfDay();
        String YY = StringUtils.leftPad(year.toString(), 2, "0");
        String DDD = StringUtils.leftPad(day.toString(), 3, "0");
        String SSSSSS = StringUtils.leftPad(second.toString(), 6, "0");
        dateString = YY   DDD   SSSSSS;
        return dateString;
    }

We have utmost 100 concurrent users at time and it is having performance impact and causing unique constraint exception when generated id is stored to the DB.

Is there any better solution to this issue.

Note : The business requirement is to have 11 digits only.

CodePudding user response:

First things first - maybe you should get back to business and verify why they need 11 digits constraint ;)

Anyway if particular user can make only one request at a time (i.e. no concurrent request from single user) I would include user id (or some part of it) in generated id. In such case generated ids should not overlap.

CodePudding user response:

I think I probably did not get the question but I will do my best.

perhaps a better way would be to use UUIDs? is using timestamp a requirement?

I added an example below

    public static String generateId() {
    //Create new uuid
    UUID uuid = UUID.randomUUID();
    //Convert the uuid to string and strip it from "-"
    String id = uuid.toString().replace("-", "");
    //Trim the UUID and retrieve the chars until the 11th char.
    id = id.substring(0, 11);
    //Return the id back
    return id;
}
  •  Tags:  
  • Related