Search code examples
javaspring-boothibernateuuid

UUID column autogenerated without @Id anotation


I have a table and there is already id defined, but for some reason I need the uuid column to be auto generated and unique.

I tried all kind of annotations like this, but nothing seems to work:

@Column(columnDefinition = "BINARY(16)")
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")

Is it possible without defining uuid as @Id? Thanks.

public class EntityClass {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   private UUID uuid;
}

Solution

  • Actually, I did it this way:

    public class EntityClass {
    
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private Long id;
    
       @Column(unique = true, nullable = false)
       private UUID uuid = UUID.randomUUID();
    }
    

    On initial save, UUID will be set, and it should be unique and not null.