em.createNativeQuery executes first than em.persist and now?

3

I'm developing an application with Hibernate + Spring mv. spring takes care of EntityManager dependency for my DAO, however I have the following problem.

  • I persist an object called User
  • After I run createNativeQuery with "insert into table1 (field1, field2) select field1, field2 from User"

I noticed that in table1 I was not registering the User, I checked to enable show_sql and in the console hibernate first runs the createNativeQuery after the persist, regardless of the order the two were written.

Is there any way to configure hibernate to keep the order?

    
asked by anonymous 08.04.2015 / 06:28

1 answer

2

The problem is caused because many of the common operations are stored in a sort of in-memory queue, which is usually downloaded to the database at one time when closing EntityManager . Hibernate thus tries to optimize access to the database. However, native queries do not go through this queue and for DBMS it is as if the first command had never occurred.

The ideal in this case is to execute the flush() method after the persist() to force that the commands waiting in the queue were sent to the database, in this case the insertion.

    
08.04.2015 / 20:48