简体   繁体   English

在Hibernate中自动生成带注释的字符串主键

[英]Auto Generate String Primary Key with Annotation in Hibernate

I'm pretty new to Spring Boot and in the model there's an Id (primary key) which is String and I need to auto-generate it when saving new entity. 我对Spring Boot还是很陌生,在模型中,有一个ID(主键)是String,保存新实体时需要自动生成它。

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private String name;
private String description;

But, I get this error when saving a new entity. 但是,保存新实体时出现此错误。

"message": "Unknown integral data type for ids : java.lang.String; nested exception is org.hibernate.id.IdentifierGenerationException: 

How to avoid this error and do the auto generation id when a new entity is saved. 保存新实体时如何避免此错误并执行自动生成id

This is not working for you as you attempt to use the auto generated value with a String field. 当您尝试将auto生成的值与String字段一起使用时,这对您不起作用。

In order for this to work you need to change your @GeneratedValue annoation to use a generator instead of a strategy and also add a @GenericGenerator annotation naming the generator and poininting over to the strategy. 为了使它起作用,您需要更改@GeneratedValue注释以使用generator而不是strategy并且还添加一个@GenericGenerator批注,命名生成器并指向该策略。

Assuming for example that you want to produce auto-generated UUIDs as PKs for your table, your code would look like: 例如,假设您要为表生成自动生成的UUID作为PK,则代码如下所示:

@Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
        name = "UUID",
    strategy = "org.hibernate.id.UUIDGenerator"
    )
@Column(updatable = false, nullable = false)
private String id;

Aside for the above, you can always implement IdentifierGenerator to create your own generators. 除了上述内容,您始终可以实现IdentifierGenerator来创建自己的生成器。 You can check here for more: 您可以在此处查看更多信息:

How to implement a custom String sequence identifier generator with Hibernate 如何使用Hibernate实现自定义字符串序列标识符生成器

@GeneratedValue(strategy = GenerationType.AUTO) This will result in any of either identity column, sequence or table depending on the underlying DB. @GeneratedValue(strategy = GenerationType.AUTO)这将导致标识列,序列或表中的任何一个,具体取决于基础数据库。

If you look here, you'll notice all of those generate ids of type long, short or int, not of type String. 如果您在此处查看,您会注意到所有这些生成类型为long,short或int而不是String类型的id。

If you want to generate Id as the string then use generator="uuid" as follows 如果要生成Id作为字符串,请按以下方式使用generator =“ uuid”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM