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.
@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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With