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