Using Hibernate UUIDGenerator via annotations

后端 未结 8 623
无人共我
无人共我 2020-12-04 10:31

I\'m using my uuid as following:

@Id
@GeneratedValue(generator = \"uuid\")
@GenericGenerator(name = \"uuid\", strategy = \"uuid\")
@Column(name = \"uuid\", u         


        
相关标签:
8条回答
  • 2020-12-04 11:04

    Unknown Id.generator: hibernate-uuid

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id", unique = true)
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    0 讨论(0)
  • 2020-12-04 11:05

    As @natan pointed out in a comment, if you are using Hibernate 5 the below code is sufficient:

    @Id 
    @GeneratedValue
    private java.util.UUID id;
    

    Define the id column with the type of BINARY(16) in MySQL or it's equivalent in other SQL implementations.

    0 讨论(0)
  • 2020-12-04 11:11

    It should be uuid2:

    ...
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    ...
    

    See 5.1.2.2.1. Various additional generators.

    0 讨论(0)
  • 2020-12-04 11:12

    This will use UUID v4 and the auto generated uuid will be stored in the column as usual varchar(36):

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(length = 36)
    private String uuid;
    

    This should have some performance impact:

    • consumed size is more than BINARY(16)
    • after hydration the java.lang.String instance consumes more memory than java.util.UUID: 112 bytes for UUID as string versus 32 bytes (i.e. two longs + obj header) for UUID.

    But it's much more easier to work with string'ed UUID - easier to write queries and you can see the contents of the table.

    Tested on Hibernate 5.3

    0 讨论(0)
  • 2020-12-04 11:19

    HibernateDoc says you can use following:

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

    I hope you are using Hibernate 3.5.

    0 讨论(0)
  • 2020-12-04 11:20

    Try...

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "uuid", columnDefinition = "BINARY(16)")
    public UUID getId()
    {
        return id;
    }
    
    public void setId(UUID i)
    {
        id = i;
    }
    

    Note the "uuid2" as opposed to "uuid".

    0 讨论(0)
提交回复
热议问题