首页 > 解决方案 > How to make a JPA sequence generate sequence Id in sync with external system using same DB concurrently

问题描述

I am using a sequence which basically generates id b/w 1000 to 9999 while inserting record in database table. Now there is an external legacy system (GUI) which creates that record by manually mentioning id b/w 1000 to 9999.Before deploying my application there are already some records is table like below:

Employee Table

I have applied the sequence in my entity like below:

@Id
    @GenericGenerator(
            name = "empid-sequence-generator",
            strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                    @Parameter(name = "sequence_name", value = "user_sequence"),
                    @Parameter(name = "initial_value", value = "1000"),
                    @Parameter(name = "increment_size", value = "1")
            }
    )
    @GeneratedValue(generator = "empid-sequence-generator")
    @Column(name = "EMP_ID", nullable = false)
    public short getEmp_id() {
        return emp_id;
    }

With the current sequence implementation I am getting SqlServerException due to primary key clashes some of id in the range(1000-9999) is already been inserted through External System GUI.

How can i implement the current sequence so that for the first insert record will be inserted with id 1000 as it's not occupied but for the next insert will save record with id 1002 as 1001 is already exist in DB.

Thanks

标签: sql-serverhibernatejpasequence

解决方案


注意到它作为 id 生成器不能做你想做的事,你必须实现一个返回最低可用 ID 的函数,并在每次你想要执行插入以获取所述 id 以手动将其设置为实体时调用它。


推荐阅读