Search code examples
javaspringmongodbspring-bootauto-increment

Limit autoincrement @Id to 6 digit in Spring


I have a model class which as this auto increment id which returns objectId of 24 digit.

How to limit it to 6 digit only?

Model Class:

@Id 
private String id;    
    
public String getId() {
        return id;
}

Controller Class:

ValidatorClass validation = new ValidatorClass();
    
Map<String, String> objValidate = validation.getExecutorInput(model.getLink(), 
                                    model.getUsername(), model.getPassword(), model.getSolution());

repository.save(model);

String id = "Request ID: " + model.getId();

return new ResponseEntity(id, org.springframework.http.HttpStatus.OK);

Solution

  • You can annotate the field to specify further restrictions, eg.:

    @Id 
    @Column(length = 6)
    @Size(max = 6)
    private String id;
    

    Furthermore, if you want finer control over the id before persisting an entity, you can add a method annotated with @PrePersist to your entity where you can truncate/transform the id as you need, eg.:

    @PrePersist
    public void prePersist() {
      this.id = this.adapt(id);
    }