I'm having an issue with inserting new rows into my MySQL database. I'm using Spring Boot with Spring Boot Data JPA.
Since MySQL doesn't support sequences, I decided to try and make my own sequence generator table. This is basically what I've done.
- I created a
sequences
table that uses an auto increment field (used as my id's for my tables). - Created a function,
sequences_nextvalue()
which inserts into thesequences
table and returns the new auto incremented id. - I then created triggers on each table that get triggered before insertion and replaces the id field with the result of calling
sequences_nextvalue()
.
So this is working fine when inserting new rows. I'm getting unique ids across all tables. The issue I'm having is with my JPA entities.
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractBaseClass {
@Id
private Integer id = -1;
...
}
@Entity
public class ConcreteClass1 extends AbstractBaseClass {
...
}
@Entity
public class ConcreteClass2 extends AbstractBaseClass {
...
}
I want to be able to query from the abstract base class so I've placed my @Id
column in that class and used @Entity
with InheritanceType.TABLE_PER_CLASS
. I've also initialized the id to -1 since an id is required to call save()
from my spring crud repository.
After calling the save()
function of my Spring data CrudRepository
, the -1 for id
properly gets replaced by the MySQL trigger but the resulting entity returned by save()
doesn't return with the new id but instead retains the -1. After looking at the SQL logs, a select statement is not being called after insertion to get the new id but instead the original entity is being returned.
Is it possible to force Hibnerate to re-select the entity after insertion to get the new id when you're not using @GeneratedValue
?
Any help is greatly appreciated.