starting the transaction using
session.beginTransaction();
before processing entities also avoids errors, but this is even slower than manual flushing.