这是对我有用的-我们在服务中对所有代码进行了编码。这是实体:
@Entity@Inheritance(strategy = InheritanceType.SINGLE_TABLE)public class Registrant extends AbstractEntity { //.... private long invoiceNumber;//invoice number @Entity public static class InvoiceNumberGenerator { @Id @GeneratedValue private int id; private long counter; public int getId() { return id; } public void setId(int id) { this.id = id; } public long getCounter() { return counter; } public void setCounter(long counter) { this.counter = counter; } }}
然后,我们有一个执行魔术的服务(实际上没有魔术,所有 *** 作都是手动完成的):
public synchronized Registrant save(Registrant registrant) { long counter = getInvoiceNumber(); registrant.setInvoiceNumber(counter); return registrantRepository.save(registrant);}private long getInvoiceNumber() { //mist: get the invoice number from the other table long count = registrantInvoiceNumberGeneratorRepository.count(); if(count > 1) { throw new RuntimeException(": InvoiceNumberGenerator table has more than one row. Fix that"); } Registrant.InvoiceNumberGenerator generator; if(count == 0) { generator = new Registrant.InvoiceNumberGenerator(); generator.setCounter(1000001); generator = registrantInvoiceNumberGeneratorRepository.save(generator); } else { generator = registrantInvoiceNumberGeneratorRepository.findFirstByOrderByIdAsc(); } long counter = generator.getCounter(); generator.setCounter(counter+1); registrantInvoiceNumberGeneratorRepository.save(generator); return counter;}
注意
synchronized方法-这样没人能得到相同的号码。
我不敢相信没有自动装置可以做到这一点。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)