加入收藏 | 设为首页 | 会员中心 | 我要投稿 鄂州站长网 (https://www.0711zz.com/)- 数据分析、网络、云渲染、应用安全、大数据!
当前位置: 首页 > 数据库 > MySql > 正文

mysql – 如何在Hibernate中为每个公司创建一个customerNumber生成器

发布时间:2020-11-18 08:49:38 所属栏目:MySql 来源:互联网
导读:我有一个客户表,每个客户都属于一个公司,公司希望他们的客户编号从0开始并随着他们添加客户而增加,当公司B添加客户时,公司A的客户编号不应受到影响. CustomerId内部可以是任意数字,customerNumber必须在companyId的上下文中无间隙递增(无间隙我的意思是0,1,2,

我有一个客户表,每个客户都属于一个公司,公司希望他们的客户编号从0开始并随着他们添加客户而增加,当公司B添加客户时,公司A的客户编号不应受到影响. CustomerId内部可以是任意数字,customerNumber必须在companyId的上下文中无间隙递增(无间隙我的意思是0,1,2,3,4,如果2被删除,它已经消失,下一个插入应该是5而不是2)

Example: 
    companyId customerNumber  customerId 
    0         0               0
    0         1               1
    0         2               2
    0         3               3
    0         4               4
    0         5               5
    1         0               6
    1         1               7
    1         2               8

我想知道是否有更好的方法来做它而不是打开一个事务,找到max customerNumber,使用max 1作为customerNumber插入一个条目并关闭事务

我可以使用某种注释来指定生成customerNumber的条件吗?下一个customerNumber应该是该公司内可用的最高数量. (我有大约20个基于日期和comapnyId具有类似的人类可读增量id要求的其他实体,我想尽可能使customerNumber类型字段生成为万无一失,我不想记得每次我坚持一个新实体时这样做)

就像是:

@SequenceGenerator(uniqueOver="companyId,customerNumber",strategy=GenerationType.AUTO)
private Long customerNumber;

由于我正在使用股票和财务数据,因此该解决方案应符合ACID标准.

更新:我已将id重命名为customerId,将customerId重命名为customerNumber以防止混淆.

更新:
当我的意思是无间隙时,我的意思是customerNumbers应该是0,5,6,7,8,9 – 如果我删除了4号,它将永远消失,下一个插入应该是10,除非我创建了一家新公司,然后他们的第一个客户应该从0开始.

更新:
我正在使用带休眠的spring,所以@PrePersist注释对我来说不起作用.如果@PrePersist被建议作为解决方案,那么它需要在spring下工作,因此需要回答Simon的问题:Enable @PrePersist and @PreUpdate in Spring

建议的答案,我不确定:

@Entity
@Table(name = "Customer")
public class Customer {

    @Table(name = "CustomerNumber")
    @Entity(name = "sequenceIdentifier")
    public static class CustomerNumberSequenceIdentifier {

        @Id
        @GenericGenerator(name = "sequence",strategy = "sequence",parameters = {
                @org.hibernate.annotations.Parameter(name = "sequenceName",value = "sequence"),@org.hibernate.annotations.Parameter(name = "allocationSize",value = "1"),})
        @GeneratedValue(generator = "sequence",strategy=GenerationType.SEQUENCE)
        private Long id;

    }


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long customerId;

    @ManyToOne
    private Company company;

    @GeneratedValue(generator = "sequenceIdentifier",strategy=GenerationType.TABLE)
    private Long customerNumber

}
最佳答案 如果你使用hibernate;
示例查询


查询query = session.createQuery(“insert into customer(company_id,customer_id)”“(select:company_id,IFNULL(max(customer_id),1)1 from customer where company_id =:company_id)”);

    //set the company_id here

    int result = query.executeUpdate();

注意:IFNULL是一种MYSQL特定语法

我建议将公司ID auto_increment字段保存在单独的公司主表中.

(编辑:鄂州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读