栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/435986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号