Auto Generate String Primary Key with Annotation in Hibernate

人走茶凉 提交于 2019-12-08 08:24:31

问题


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.

@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.


回答1:


This is not working for you as you attempt to use the auto generated value with a String field.

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.

Assuming for example that you want to produce auto-generated UUIDs as PKs for your table, your code would look like:

@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. You can check here for more:

How to implement a custom String sequence identifier generator with Hibernate




回答2:


@GeneratedValue(strategy = GenerationType.AUTO) This will result in any of 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.

If you want to generate Id as the string then use generator="uuid" as follows

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


来源:https://stackoverflow.com/questions/51998450/auto-generate-string-primary-key-with-annotation-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!