When does Spring Data JPA actually call INSERT on the database?

Viewed 6192

When you save an object using JPARepository/Hibernate, it first checks if it exists (using Primary Key) in the database, and then Inserts. So we see 2 logs: SELECT & INSERT.

This is what I'm trying to do through spring data: (X and XY are 2 distinct objects)

Call Save on XRepository for Object X1

Call Save on XYRepository for Object X1Y1
Call Save on XYRepository for Object X1Y2
Call Save on XYRepository for Object X1Y3

Call Save on XRepository for Object X2

Call Save on XYRepository for Object X2Y1
Call Save on XYRepository for Object X2Y2
Call Save on XYRepository for Object X2Y3

This is my observation in the logs:

SELECT X1
INSERT X1
SELECT X1Y1
SELECT X1Y2
SELECT X1Y3
INSERT X1Y1
INSERT X1Y2
INSERT X1Y3
SELECT X2
INSERT X2
SELECT X2Y1
SELECT X2Y2
SELECT X2Y3
INSERT X2Y1
INSERT X2Y2
INSERT X2Y3

So when does Spring Data actually call the insert? How does this work?

This is what i had expected:

SELECT X1
INSERT X1
SELECT X1Y1
INSERT X1Y1
SELECT X1Y2
INSERT X1Y2
SELECT X1Y3
INSERT X1Y3
...
2 Answers
Related