0

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.

vb210
  • 1
  • It sounds like maybe you want a repeatable read isolation level. http://stackoverflow.com/questions/8490852/spring-transactional-isolation-propagation – Terry Jul 01 '15 at 00:13
  • Turns out I needed a serializable isolation level. I ran a test by spawning several hundred threads and with repeatable_read, duplicate id's were being generated. Since serializable greatly impacts performance, I created a separate entity to maintain these Ids and perform the generation, which should prevent locking out the DocumentType entity. One additional point to note, JPA with Spring does not seem to support Isolation levels, and therefore I needed to extend the HibernateJpaDialect class. [link](http://stackoverflow.com/questions/5234240/hibernatespringjpaisolation-does-not-work) – vb210 Jul 03 '15 at 00:26

0 Answers0