java - 如何在 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
字段下包含字符串值,所以我想更改Long
为String
.
解决方案
我应该使用以下两行:
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
代替
@GeneratedValue
推荐阅读
- image - 从不以 .jpeg 结尾的 URL 下载图像
- string - 如何将字符串列表拆分为列表中的字符串列表?
- c - 阶乘函数只数到 12
- git - 将提交移动到 Visual Studio 中的不同分支?
- reactjs - 寻找如何使用 React i18n 的确认
- regex - 仅在具有特定前缀的文件中搜索 IntelliJ 中的文本
- azure-devops - 发出会话令牌时出错:HostAuthorizationNotFound
- django - Django Rest Framework 分页和过滤
- ansible - 如果标准输出结果等于失败,如何使用 Ansible 重新启动服务器?
- filesystems - MTDBLOCK1 似乎被嵌入式 Linux 系统上的 SD 卡内容覆盖