title: Correct use of flush() in JPA/Hibernate
body: <p>I was gathering information about the flush() method, but I'm not quite clear when to use it and how to use it correctly. From what I read, my understanding is that the contents of the persistence context will be synchronized with the database, i. e. issuing outstanding statements or refreshing entity data.</p>
  
  <p>Now I got following scenario with two entities <code>A</code> and <code>B</code> (in a one-to-one relationship, but not enforced or modelled by JPA). <code>A</code> has a composite PK, which is manually set, and also has an auto-generated IDENTITY field <code>recordId</code>. This <code>recordId</code> should be written to entity <code>B</code> as a foreign-key to <code>A</code>. I'm saving <code>A</code> and <code>B</code> in a single transaction. The problem is that the auto-generated value <code>A.recordId</code> is not available within the transaction, unless I make an explicit call of <code>em.flush()</code> after calling <code>em.persist()</code> on <code>A</code>. (If I have an auto-generated IDENTITY PK then the value is directly updated in the entity, but that's not the case here.)</p>
  
  <p><strong>Can <code>em.flush()</code> cause any harm when using it within a transaction?</strong></p>