Flush called during a flush

Hello,

As part of an integration test :

I added a listerner PostCollectioncreateEventListener to update the database when creating a list.
I then use a createNativeQuery to update a column that is not known to hibernate.

but if I don’t set the flushMode to Commit, it causes a unique key constraint because it tries to reinsert the same objects from the list.

What I understood is as we are in the execution of a flush and that the NativeQuery causes a flush by default, it then re-executes all the instructions of the current flush.

Normal ?

Thanking you

If you look into org.hibernate.query.sql.internal.NativeQueryImpl#prepareForExecution you will see that unless you have specified synchronizedQuerySpaces, Hibernate chooses to be pessimistic and flushes everything. As you have noted, running a query that causes flushing within the flush execution is problematic and generally unsupported. What you can do though, is add "" i.e. the empty string to synchronizedQuerySpaces, which would avoid this. I guess that changing the flush mode on the query is another way to avoid this, but specifying synchronizedQuerySpaces is IMO more future proof.

Overall, yes, the flushing behavior is intended. It’s unfortunate that it happens while another flush is going on, but since this is something that Hibernate doesn’t officially support, we are in a grey area and only fix issues here on a best effort basis. So if you want something to be fixed, you’d have to fix it yourself.

Thanks ! It was just to know if it was a case to be avoided.
So the answer is yes and that’s fine with me. :slight_smile: