Hibernate / MyBatis Interview questions
How does MyBatis handle transactions, and how does it integrate with Spring's transaction management?
In plain, non-Spring MyBatis usage, transaction boundaries are managed directly through the SqlSession — an explicit commit() persists changes, an explicit rollback() discards them, and by default a session is not in auto-commit mode, meaning a developer is responsible for calling one or the other before closing the session.
@Transactional public void transferFunds(int fromId, int toId, BigDecimal amount) { accountMapper.debit(fromId, amount); accountMapper.credit(toId, amount); // Spring commits or rolls back automatically based on method outcome }
In a Spring-managed application, MyBatis-Spring replaces this manual model entirely: SqlSessionTemplate ties MyBatis's operations to Spring's own transaction infrastructure, so a method annotated with @Transactional (as shown above) automatically commits if it completes successfully or rolls back if it throws an exception, without any explicit commit()/rollback() calls in application code at all.
This integration is specifically what lets a single @Transactional method safely call multiple mapper methods (as in the funds-transfer example) and have them all commit or roll back together as one atomic unit, which is a natural, expected requirement for any non-trivial business operation touching more than one row or table, and is far more error-prone to get right with manual commit/rollback calls scattered through application code.
More Related questions...