How to make string primary key hibernate. @GeneratedValue strategies

前端 未结 3 596
走了就别回头了
走了就别回头了 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: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.

提交回复
热议问题