Let\'s first forget about Hibernate. Assume that I have two tables, A & B. Two transactions are updating same records in these two tables, but txn 1 update B and then
Regarding first example - this kind of stuff is handled by database (read more about transaction isolation levels and locking strategies of your database). There are many different ways this can be handled.
As to Hibernate, javadoc to org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(EventSource) says:
Execute all SQL and second-level cache updates, in a special order so that foreign-key constraints cannot be violated:
I assume that this is the only optimization of executed SQL queries Hibernate makes. The rest of problems is handled by database.