简体   繁体   中英

Overriding id generated by sequence

I am using SequenceGenerator for generating a primary key for my entities. Now there is a use case wherein I need to use the given id instead of the id generated by the sequence.

I tried setting the id field by given value and saving it but the custom id has been overridden by the sequence. So is there any way to tell the hibernate to use the given id if it is not null or generate a new one using sequence if the id is not set explicitly?

My current id generator

    @Id
    @SequenceGenerator(name = "userSeqGen", sequenceName = "userSeq", initialValue = 100, allocationSize = 50)
    @GeneratedValue(generator = "userSeqGen")
    private Integer id;

If the @Id field of an entity does not have @GeneratedValue , it allows you to assign the ID for that entity manually.

That means you can create another entity that maps to the same table for the use-case that require to manually configure the ID and use the entity with @GeneratedValue for the normal case.

By using some inheritance design, you may have something like:

@MappedSuperclass
public class Employee  {

    @Column
    private String email;

    @Column
    private String title;
    
    ......
}
@Entity
@Table(name="employee")
public class DefaultEmployee extends Employee {

    @Id
    @SequenceGenerator(name = "userSeqGen", sequenceName = "userSeq", initialValue = 100, allocationSize = 50)
    @GeneratedValue(generator = "userSeqGen")
    private Integer id;
}
@Entity
@Table(name="employee")
public class ManuallyAssignedIdEmployee extends Employee {

    @Id
    private Integer id;

    public ManuallyAssignedIdEmployee(Integer id){
       this.id = id;
    }


}

If you need to create an employee with manually assigned id, create ManuallyAssignedIdEmployee instance. Otherwise, create DefaultEmployee instance.

Please note that since you are manually assigned ID for some cases, it is your responsibility to make sure that the manually assigned ID will not mess up with the ID that is auto-generated from the DB sequence. (eg the manually assigned Id is already auto-generated and used by other records or the auto-generated ID in the future cannot be used as you already manually assigned it to some records in the past etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM