如何在 JPA/Hibernate 中使用带有字符串类型的@Id? [英] How to use @Id with String Type in JPA / Hibernate?

查看:45
本文介绍了如何在 JPA/Hibernate 中使用带有字符串类型的@Id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串类型主键的实体.这个实体模型如下:

I have one entity which contains primary key of type string. This entity model is as follows:

@Entity
public class MyEntity {

@Id
@Column(name="PR_KEY", unique=true)
private String prKey;

....
....

}

但我遇到了 TypeMismatch 的问题.

But I am facing issue saying TypeMismatch.

org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.String, got class java.lang.Long

推荐答案

如果不指定 id 生成策略,Hibernate 将使用 GenerationType.AUTO.这将导致任何

If you don't specify an id generation strategy, Hibernate will use GenerationType.AUTO. This will result in any of

AUTO - 标识列、序列或表,具体取决于底层数据库.

AUTO - either identity column, sequence or table depending on the underlying DB.

如果您查看此处,您会注意到所有这些都生成 longshortint 类型的 id,而不是 String 类型.

If you look here, you'll notice all of those generate ids of type long, short or int, not of type String.

假设你想要一个 String UUID 作为 id,你可以使用

Say you wanted a String UUID as an id, you could use

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "PR_KEY")
private String prKey;

这篇关于如何在 JPA/Hibernate 中使用带有字符串类型的@Id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆