如何在spring启动时使用Hibernate生成自动UUID [英] How to Generate an auto UUID using Hibernate on spring boot
问题描述
我试图实现的是生成一个在数据库插入期间自动分配的UUID。类似于生成id值的名为id的主键列。
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;
但是当DB插入完成时。 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.
推荐答案
你可以使用一些像@PrePersist这样的事件来填充UUID字段
https:// docs。 jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html
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
但为何在创建对象时不分配uuid uuid = UUID.randomUUID()?
but why just not assign uuid when object is created uuid = UUID.randomUUID() ?
这篇关于如何在spring启动时使用Hibernate生成自动UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!