如何在JPA / Hibernate中使用@Id和String类型? [英] How to use @Id with String Type in JPA / Hibernate?

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

问题描述

我有一个包含string类型主键的实体。这个实体模型如下:

  @Entity 
public class MyEntity {

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

....
....

}

但是我面临的问题是TypeMismatch。

  org.hibernate.TypeMismatchException:错误的类型。预期:class java.lang.String,得到类java.lang.Long 


解决方案如果你不指定一个id生成策略,Hibernate将使用 GenerationType.AUTO 。这将导致任何


AUTO - 根据
底层数据库,标识列,序列或表格。


如果您看,你会注意到所有这些生成类型为 long ,的id 或 int ,不是类型字符串



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

  @Id 
@GeneratedValue(generator =uuid)
@GenericGenerator(name =uuid,strategy =uuid2)
@Column(name = PR_KEY)
私人字符串prKey;


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.

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

解决方案

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

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

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

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和String类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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