How to make string primary key hibernate. @GeneratedValue strategies

前端 未结 3 595
走了就别回头了
走了就别回头了 2020-12-10 16:23

My goal is to create an entity Device that has a unique field IMEI and I would like to use it as a primary key, and specify it at device registration time (manually specifie

相关标签:
3条回答
  • 2020-12-10 17:12

    A straightforward solution could be to use the @PrePersist annotation on your entity class.

    Simply add the method

    @PrePersist
    private void ensureId(){
        this.setId(UUID.randomUUID().toString());
    }
    

    and get rid of the @GeneratedValue annotation.

    PrePersist documentation: http://docs.oracle.com/javaee/5/api/javax/persistence/PrePersist.html

    Stefano

    0 讨论(0)
  • 2020-12-10 17:19

    At the moment, it may be unnecessary. But I think we should update this ticket for someone.

    I'm new to answering on stack overflow, so hopefully this makes sense

    If you want to generate String as ID in hibernate automatically, you can define a rule using IdentifierGenerator and @GenericGenerator.

    Entity declaration:

    public class Device {...
    
        @Id
        @GenericGenerator(name = "sequence_imei_id", strategy = "com.supportmycode.model.ImeiIdGenerator")
        @GeneratedValue(generator = "sequence_imei_id")
        @Column(name = "IMEI")
        private String IMEI;
    
    ...}
    

    Imei Generator Declaration:

    public class ImeiIdGenerator implements IdentifierGenerator {...
        public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
    
                // define your IMEI, example IMEI1, IMEI2,...;
                return "IMEI"+ UUID.randomUUID().toString();
    ...}
    

    When you save a Device object, IMEI(id) will be generate automatically by ImeiIdGenerator.

    0 讨论(0)
  • 2020-12-10 17:29

    @GeneratedValue(strategy = GenerationType.AUTO) cannot be used with String type. So, if you want to use String as ID, you have to assign it manually. But it is fine to use String as ID if it suits your need.

    Using org.hibernate.id.Assigned also means that you have to assign the ID value before saving the data.

    When @GeneratedValue annotation is not added, the default is assigned generator which means the value of identifier has to be set by the application.

    Please refer to the hibernate manual for details.

    0 讨论(0)
提交回复
热议问题