How to make string primary key hibernate. @GeneratedValue strategies

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


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.


@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.