5

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.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36
Tharindu Thisarasinghe
  • 3,846
  • 8
  • 39
  • 70

2 Answers2

6

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

akortex
  • 5,067
  • 2
  • 25
  • 57
6

@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;
Pankaj Saboo
  • 1,125
  • 1
  • 8
  • 27