Home > Mobile >  Do I have to set ID value in hibernate entity
Do I have to set ID value in hibernate entity

Time:04-04

Do I have to set the ID value in entity class in hibernate, When I don't set the value for ID It shows "Column 'ID' doesn't have default value". Datatype for the column is Decimal, but when I use same database in Oracle I didn't get error like this. I was seeing this error when I'm using MySQL. Could you give me an suggestion.

CodePudding user response:

A common approach is to define the ID with an autoIncrement type. This let's the database assign the next available ID to that field. So then you don't have to set a value from the code (which could potentially fail if another thread on the server attempts to create an instance of that entity at the same moment).

The resulting ID value will be present in the returned entity instance after creation.

For example you can define such an ID field using JPA annotations as follows:

@javax.persistence.Id @javax.persistence.GeneratedValue
private Long id;

See also: https://www.baeldung.com/hibernate-identifiers

  • Related