Multiple write sessions in the same request
Writing to the database from more then one sessions in the same request it is bad for several reasons. Here is why:
- Each session uses a separate database connection. Using more than one session means using more than one database connection per request. This can hurt overall performance, and puts more pressure on the database.
- Using different session mean that we cannot take advantage of the Hibernate built-in transaction support and have to rely on two phased commits which is significantly slower.
- We can't rely on the database to ensure transactionally safe view of the data, since we are using several different transactions to access the database. Note that this is the case even when using two phased commits.
- Using two phased commits can lead to bad performance and is more brittle than not using it.
- Without using two phased commits, there is no ability to use transaction across all the session.
For example, let us consider the following code, which is using multiple sessions to perform a single operation:
public void transferMoney(Account from, Account to, Money amount) { Dao.withdraw(from, amount); Dao.deposit(to, amount); } public void withdraw(Account account, Money amount) { Session session = sessionFactory.openSession(); session.beginTransaction(); account.moenyAmount -= amount; session.update(account); session.getTransaction().commit(); session.close(); } public void deposit(Account account, Money amount) { Session session = sessionFactory.openSession(); session.beginTransaction(); account.moenyAmount += amount; session.update(account); tx.commit(); session.getTransaction().commit(); session.close(); }
In this example, we call to the database twice, each time from different session. Because of that, we cannot take advantage of the database native transaction support, since each operation happen in a different transaction. Our choices are to either operate essentially without transactions (in which case, money can literally disappear in the air), or participate in a distributed transaction (two phased comments).