I am using Spring with JPA and have 2 entities:
public class DocumentType {
@Id
@GeneratedValue
private Long id;
private String name;
private String idPrefix;
private Integer maxNumberOfSuffixDigits;
private Long startingSuffixNumber;
private String nextDocId;
...
}
public class Document {
@Id
private String id;
@ManyToOne
@JoinColumn
private DocumentType documentType;
...
}
Many Documents can be mapped to the same DocumentType, and there can be many DocumentTypes. The id for the Document will be generated using the combination of parameters found in it's corresponding DocumentType which is: idPrefix + startingSuffixNumber prefixed with 0s to meet the maxNumberOfSuffixDigits constraint. Currently I am on the fence of whether or not I will store the pre-generated nextDocId, but for the purposes of this question (if it makes the solution easier) let's assume that it is available.
The problem I have is getting the nextDocId, and generating the following Id in a concurrent environment. I've looked into Pessimistic write locks, but I do not think that can solve this issue, as from what I've seen, it only locks a single query. I need a way to somehow lock two queries: select query on the nextDocId, followed immediately by an update to generate a new nextDocId.
Any suggestions on how I can achieve this, or other alternatives to this problem would be greatly appreciated.