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

Jan*_*ert 5 mysql orm hibernate jpa hibernate-mapping

我有一个客户表,每个客户都属于一个公司,公司希望他们的客户编号从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
Run Code Online (Sandbox Code Playgroud)

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

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

就像是:

@SequenceGenerator(uniqueOver="companyId,customerNumber",strategy=GenerationType.AUTO)
private Long customerNumber;
Run Code Online (Sandbox Code Playgroud)

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

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

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

更新:我正在使用spring with hibernate,所以@PrePersist注释对我不起作用.如果@PrePersist被建议作为解决方案,那么它需要在spring下工作,因此需要回答Simon的问题:在Spring中启用@PrePersist和@PreUpdate

建议的答案,我不确定:

@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

}
Run Code Online (Sandbox Code Playgroud)

God*_*win 1

如果你使用休眠;查询示例

Query 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();
Run Code Online (Sandbox Code Playgroud)

注意:IFNULL是MYSQL特定的语法

我建议将公司 IDauto_increment字段保留在单独的公司主表中。