I see inconsistent hibernate behavior when using sequence to generate id, I have simple project with one entity Fruit and I'm using spring.jpa.hibernate.ddl-auto=create-drop
so hibernate is launching create sequence fruit_seq start with 1 increment by 50 nocache
now the issue is when I create fruits in following sequence
curl --location 'http://localhost:8080/fruits' \
--header 'Content-Type: application/json' \
--data '{
"name": "apple"
}'
curl --location 'http://localhost:8080/fruits' \
--header 'Content-Type: application/json' \
--data '{
"name": "mango"
}'
then run this query manually
select next value for fruit_seq; -- returns 101
then again I create a third fruit
curl --location 'http://localhost:8080/fruits' \
--header 'Content-Type: application/json' \
--data '{
"name": "orange"
}'
I get id correctly without any affect from my external next_val query that returned 101
MariaDB [fruits]> select * from fruit;
+----+------------+
| id | fruit_name |
+----+------------+
| 1 | apple |
| 2 | mango |
+----+------------+
2 rows in set (0.001 sec)
MariaDB [fruits]> select next value for fruit_seq;
+--------------------------+
| next value for fruit_seq |
+--------------------------+
| 101 |
+--------------------------+
1 row in set (0.001 sec)
MariaDB [fruits]> select * from fruit;
+----+------------+
| id | fruit_name |
+----+------------+
| 1 | apple |
| 2 | mango |
| 3 | orange |
+----+------------+
3 rows in set (0.001 sec)
however when I do same experiment just change the order in which I create fruits and externally manipulate next_val hibernate reflect the external effect
curl --location 'http://localhost:8080/fruits' \
--header 'Content-Type: application/json' \
--data '{
"name": "apple"
}'
then run this query manually
select next value for fruit_seq; -- returns 51
then create second and third fruit
curl --location 'http://localhost:8080/fruits' \
--header 'Content-Type: application/json' \
--data '{
"name": "mango"
}'
curl --location 'http://localhost:8080/fruits' \
--header 'Content-Type: application/json' \
--data '{
"name": "orange"
}'
this affects the ids generated by hibernate
MariaDB [fruits]> select * from fruit;
+----+------------+
| id | fruit_name |
+----+------------+
| 1 | apple |
+----+------------+
1 row in set (0.001 sec)
MariaDB [fruits]> select next value for fruit_seq;
+--------------------------+
| next value for fruit_seq |
+--------------------------+
| 51 |
+--------------------------+
1 row in set (0.001 sec)
MariaDB [fruits]> select * from fruit;
+----+------------+
| id | fruit_name |
+----+------------+
| 1 | apple |
| 52 | mango |
| 53 | orange |
+----+------------+
3 rows in set (0.001 sec)
I was expecting hibernate to always get affected by external manipulations but it does not in the case when you off start by 2 fruits