Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving null as id, with hibernate [duplicate]

I'm in a strange position where I need to save @Id of an @Entity as null

The whole project is build using hibernate and entities. But for this one legacy entity, there is a trigger in the table itself to generate ID.

As a result, trying to insert anything but null will result in an error.

When trying to .save() an entity with null id, hibernate will throw

org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save()

EDIT:

Clarification, i need to do .save() where ID column is null because:

Trigger in the table will (before any insert) check if ID is null, then do SELECT to get the last ID and increment that by 1 and finally insert this new row to table. The trigger will error in case ID is anything but null.

like image 258
Clomez Avatar asked Oct 16 '22 12:10

Clomez


1 Answers

Just mark the id as autogenerated by the underlying database:

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;

GenerationType.IDENTITY is generally designed for when the PK is set as auto increment but, from the JPA point of view, it is just moving the duty of generating the id to the database engine. And thats happening in your case by the usage of a trigger.

like image 200
Maciej Kowalski Avatar answered Oct 18 '22 15:10

Maciej Kowalski