Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UUIDs with Hibernate as a field?

I'm trying to use generated UUIDs without @Id annotation, because my primary key is something else. The application does not generate an UUID, do you have an idea?

This is my declaration:

@Column(name = "APP_UUID", unique = true)
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String uuid;

I'm using Hibernate 4.3.0 with Oracle10g.

like image 853
Florian Mozart Avatar asked Mar 03 '14 14:03

Florian Mozart


3 Answers

Check the Javadoc of GeneratedValue:

Provides for the specification of generation strategies for the values of primary keys.

With other words - it is not possible with just an annotation to initialize a 'none ID' attribute.

But you can use @PrePersist:

@PrePersist
public void initializeUUID() {
    if (uuid == null) {
        uuid = UUID.randomUUID().toString();
    }
}
like image 173
Tobias Liefke Avatar answered Oct 07 '22 00:10

Tobias Liefke


try this it may help

@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "uuid", unique = true)
private String uuid;

read this link read hibernate documents it is possible

like image 23
Engineer Avatar answered Oct 07 '22 00:10

Engineer


It's not because your UUID is a primary key that it's mandatory to have it annoted with @GeneratedValue.

For example, you can do something like this :

public class MyClass
{
   @Id
   private String uuid;

   public MyClass() {}

   public MyClass (String uuid) {
      this.uuid = uuid;
   }
}

And in your app, generate a UUID before saving your entity :

String uuid = UUID.randomUUID().toString();
em.persist(new MyClass(uuid)); // em : entity manager
like image 35
user3173787 Avatar answered Oct 06 '22 23:10

user3173787