JPA或Hibernate生成(非主键)列值,而不是从1开始

JPA或Hibernate生成(非主键)列值,而不是从1开始,第1张

JPA或Hibernate生成(非主键)列值,而不是从1开始

这是对我有用的-我们在服务中对所有代码进行了编码。这是实体:

@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
方法-这样没人能得到相同的号码。

我不敢相信没有自动装置可以做到这一点



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5124895.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存