Spring generate progressive unique int for entity

Tags: , , ,



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:

progressiveInt/currentyear

Here is the model:

@Entity
public class Document {
    @Id
    @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 = documentRepository.save(document);

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

        documentRepository.save(savedDoc);
    }

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?

Answer

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

@PostPersist
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.id + "/" + this.year;
}

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



Source: stackoverflow