19

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.

Tobias Liefke
  • 8,637
  • 2
  • 41
  • 58
Florian Mozart
  • 449
  • 2
  • 5
  • 14

3 Answers3

10

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();
    }
}
Tobias Liefke
  • 8,637
  • 2
  • 41
  • 58
6

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

Engineer
  • 1,436
  • 3
  • 18
  • 33
2

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
  • I know the chance to have an UUID twice is very unlikely, but it could happen. That's why I wanted hibernate to manage UUIDs. Thank you for your help – Florian Mozart Mar 03 '14 at 15:36
  • Hibernate does _nothing_ to prevent an ID - conflict (especially it does not generate a new value if the first value exists in the database already) – Tobias Liefke Oct 14 '15 at 15:25