首页 > 解决方案 > 如何在 Java Hibernate 中将 id 设为 String?

问题描述

我有以下代码:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import java.io.Serializable;

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue
    private final String id = null; // there's Long data type originally

    @Version
    private Long version;

}

如果我运行它,我会得到:

Caused by: org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String

如果我删除@GeneratedValue注释,我仍然会得到:

Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()

问题是我的对象可能在id字段下包含字符串值,所以我想更改LongString.

标签: javahibernate

解决方案


我应该使用以下两行:

@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")

代替

@GeneratedValue

推荐阅读