问题
What I am trying to achieve is generate a UUID which is automatically assigned during a DB Insert. Similar to the primary key column named "id" generating an id value.
The model values looks something like this:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private Long id;
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "uuid", columnDefinition = "BINARY(16)")
private UUID uuid;
But when the DB insert is done. the "uuid" is empty.
Help is greatly appreciated. And if I am asking an obvious stupid question I am sorry.
回答1:
u could use some events like @PrePersist to populate UUID field https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html
but why just not assign uuid when object is created uuid = UUID.randomUUID() ?
回答2:
Can you try?
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", columnDefinition = "VARCHAR(255)")
private UUID id;
回答3:
Following worked for me:
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(name = "id", updatable = false, nullable = false)
private UUID id;
来源:https://stackoverflow.com/questions/45086957/how-to-generate-an-auto-uuid-using-hibernate-on-spring-boot