Since Hibernate ORM > 5.1 there seems to be a problem with ForeignGenerator when using Hibernate with a JTA transaction manager in conjuncton with Spring 4.3+.
When not explicitly flusing the entity manager within the transaction, the EntityManager and the Hibernate session is logically closed before the transaction is commited and hence before the hibernate session is flushed. This is a spring handling implemented in org.springframework.transaction.support.ResourceHolderSynchronization.beforeCompletion()
The problem seems to be, that the ForeignGenerator uses Session.contains which in turn performs a close-check after the session has been closed.
The attached test class contains two test cases :
addRelationImplicitFlush: a failing test case relying on implict flush when the transaction is commited
addRelationExplicitFlush: a working test when explicitly flushing the entity manager within the transaction