You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@GeneratedValue插入时未自动生成UUID问题求助

解决Hibernate中非主键UUID字段自动生成失效问题

问题描述

向数据库插入记录时,需要uuid字段自动生成,但尝试多种写法后均无效,插入的记录uuid字段始终为null。已删除表重新创建,问题依然存在。

我的实体类代码如下:

public class User {

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

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

    @Column(name="firstName", nullable = false)
    private String firstName;

    ...  
 
    // (getters and setters omitted to be concise)
}

尝试过的三种写法:
1.

@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(length = 36)
private String uuid;
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", updatable = false, nullable = false, columnDefinition = "VARCHAR(36)")
private UUID id;
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID uuid;

核心原因

Hibernate默认只会自动生成主键字段的值,非主键字段仅用@GeneratedValue无法触发自动生成逻辑,这是问题的关键。

有效解决方法

方法1:数据库端设置默认值 + 实体类注解配置

  1. 修改实体类uuid字段注解:
@Column(length = 36, insertable = false, updatable = false)
private String uuid;
  1. 给数据库表的uuid字段设置默认值:
    • MySQL:ALTER TABLE user MODIFY COLUMN uuid VARCHAR(36) DEFAULT UUID() NOT NULL;
    • PostgreSQL:ALTER TABLE user ALTER COLUMN uuid SET DEFAULT gen_random_uuid();
      插入时数据库会自动生成UUID,Hibernate会在插入后自动读取该值。

方法2:应用层前置生成UUID

直接在实体类中添加持久化前的自动生成逻辑,兼容性强:

@PrePersist
public void generateUuid() {
    if (this.uuid == null) {
        this.uuid = UUID.randomUUID().toString();
    }
}

或者在无参构造方法中生成:

public User() {
    this.uuid = UUID.randomUUID().toString();
}

方法3:Hibernate专属注解触发生成(Hibernate 5.4+)

给非主键字段添加@Generated注解,告知Hibernate读取数据库生成的值:

@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(length = 36)
@Generated(GenerationTime.INSERT) // 关键注解
private String uuid;

注意事项

  • 确保uuid字段有正确的getter和setter方法,Hibernate需要通过这些方法访问字段。
  • 若用方法1,需保证Hibernate自动建表时能带上默认值(可通过spring.jpa.hibernate.ddl-auto配置控制)。

内容的提问来源于stack exchange,提问作者Elio Rahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:20:33