Java 如何在 JPA/Hibernate 中使用带有字符串类型的 @Id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18622716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:35:59  来源:igfitidea点击:

How to use @Id with String Type in JPA / Hibernate?

javahibernatejpa

提问by Kailas

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;

....
....

}

But I am facing issue saying TypeMismatch.

但是我遇到了 TypeMismatch 的问题。

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

采纳答案by Sotirios Delimanolis

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

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

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

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

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

如果你看看这里,你会发现所有的生成类型的IDS longshortint,不是类型String

Say you wanted a StringUUID as an id, you could use

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

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

回答by Gyanendra Dwivedi

Check the PR_KEY data type in database table. This problem might occur, if the column is of type Number and you are trying to map the same to String in your entity.

检查数据库表中的 PR_KEY 数据类型。如果列的类型为 Number 并且您尝试将其映射到实体中的 String,则可能会出现此问题。

Same applies to the coulmn with generated Ids.

这同样适用于具有生成 Id 的 coulmn。

回答by Mikko Maunu

When String is used as a id, same type should be used also when finding entity via Session/EntityManager:

当 String 用作 id 时,通过 Session/EntityManager 查找实体时也应使用相同的类型:

Instead of providing Long:

而不是提供 Long:

Long key = 1L;
MyEntity me = session.get(MyEntity.class, key); 
//or 
MyEntity me = entityManager.find(MyEntity.class, key); 

String should be given:

应给出字符串:

String key = "1";
MyEntity me = session.get(MyEntity.class, key); 
//or 
MyEntity me = entityManager.find(MyEntity.class, key);