Skip to content

Spring generate progressive unique int for entity

I am working on a REST api in Spring, and I’m required to save an entity Document with a protocol number which consists in:


Here is the model:

public class Document {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(unique = true)
    private String protocolNumber;

I have come up with this solution:

public void saveDocument(Document document) {
        Document savedDoc =;

        int year = Calendar.getInstance().get(Calendar.YEAR);
        String protocolNumber = savedDoc.getId() + "/" + year;

In other words I’m saving the object and updating it using the id the DB created, but I wonder if there is a better way to do this.

Anyone can help?



To have code just a bit cleaner you could use @PostPersist, so adding method like below to your Document:

private void postPersist() {
    int year = Calendar.getInstance().get(Calendar.YEAR);
    this.protocolNumber = this.getId() + "/" + year ;       

You should not need to save / persist instance again after this update. So this if you really need to have protocolNumber stored on the database.

But: this protocolNumber is also kind a transient value so you might want to consider also adding only field year into your Document, remove field protocolNumber and create a getter like:

public String getProtocolNumber() {
    return + "/" + this.year;

This way you would not need to know the id upon persisting.

1 People found this is helpful