Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 863
Tharindu Thisarasinghe Avatar asked Dec 18 '22 21:12

Tharindu Thisarasinghe


2 Answers

@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;
like image 87
Pankaj Saboo Avatar answered Feb 20 '23 21:02

Pankaj Saboo


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

like image 20
akortex Avatar answered Feb 20 '23 22:02

akortex