Java 带注释的休眠字符串主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23221096/
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-13 21:25:37  来源:igfitidea点击:

Hibernate String Primary Key with Annotation

javahibernateannotationsprimary-key

提问by sedran

I am trying to create a Privilege class with Annotations whose Primary Key is a String. I will assign them manually while inserting. Therefore no need for hibernate to generate a value for it. I'm trying to do something like that:

我正在尝试使用主键是字符串的注释创建一个权限类。我将在插入时手动分配它们。因此不需要休眠为其生成值。我正在尝试做这样的事情:

@Id
@GeneratedValue(generator = "assigned")
@Column(name = "ROLE_NAME", nullable = false)
private String roleName;

But it throws that exception:

但它抛出该异常:

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: assigned

How can I configure a Stringprimary key with annotations?

如何String使用注释配置主键?

采纳答案by JB Nizet

Since the roleNameis not auto-generated, you should simply not annotate it with @GeneratedValue:

由于roleName不是自动生成的,您不应该简单地使用以下注释对其进行注释@GeneratedValue

@Id
@Column(name = "ROLE_NAME", nullable = false)
private String roleName;

回答by Pratik Shelar

Just use the @Idannotation which lets you define which property is the identifier of your entity. You don't need to use the @GeneratedValueannotation because I don't think you want hibernate to generate this property for you.

只需使用@Id可让您定义哪个属性是实体标识符的注释。您不需要使用@GeneratedValue注释,因为我认为您不希望 hibernate 为您生成此属性。

Even in the XML configuration based approach its an optional tag and can be skipped.

即使在基于 XML 配置的方法中,它也是一个可选标签,可以跳过。

回答by Gopi

@Id
@Column(name = "USER_ID",unique=true,columnDefinition="VARCHAR(64)")
private String userId;

This worked for me by representing the columnDefinition type with column annotation during the save or update.

通过在保存或更新期间用列注释表示 columnDefinition 类型,这对我有用。