Search code examples
javaspringhibernatejpa

Spring JPA Auto Flush


I noticed that every query I do cause a flush , I know from the JPA doc the following :

When using the default AUTO flush mode, the Persistence Context should be flushed as follows:

before the transaction is committed

before running a JPQL or HQL

query before executing a native SQL query

now my question is why JPA run the insert query after the save immediatly ?

   @Transactional
    public void test() {
        Post post=new Post();
        post.setName("post 1");
        postRepository.save(post);// After this and before the sleep , the insert is executed 

        try {
            System.out.println("sleeping.....");
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        commentRepository.findAll();

    }

output :

Hibernate: insert into post (name,id) values (?,default)

sleeping.....

Hibernate: select c1_0.id,c1_0.post_id,c1_0.review from comment c1_0

shouldn't the insert happen after the sleep ?


Solution

  • Flushing means all pending changes in the persistence context will be applied to DB but the save() here will just insert one entity to DB. It will not apply all pending changes to DB and so it is not flushing.

    You can verify it by loading an existing entity from DB and make some changes on it before you save the new entity , and you can see that the modified changes in that existing entity will not be flushed to DB at save().

    If you want , you can also think that flushing mentioned in the auto flush means flushing ALL changes while save() just flush ONE change to insert a new entity which are different things.