What is your experience with Spring Data (JPA, JDBC, Redis)? What interesting problems have you encountered with @Transactional?
sobes.tech AI
Answer from AI
Experience with Spring Data:
- JPA is used for ORM with Hibernate, convenient for working with relational databases, supports lazy loading, first-level caching.
- JDBC is applied for high-performance operations when fine-tuning SQL or batch processing is needed.
- Redis is integrated via Spring Data Redis for caching and session storage.
Problems with @Transactional:
-
Proxies and internal method calls: if a method annotated with
@Transactionalis called directly from another method of the same class, a transaction is not created because Spring uses proxies. The solution is to move transactional methods to a separate bean or use AspectJ. -
Rollback on checked exceptions: by default, transactions rollback only on unchecked exceptions (RuntimeException). To rollback on checked exceptions, you need to explicitly specify
rollbackFor. -
Non-standard propagation: sometimes it is challenging to choose the correct propagation (e.g.,
REQUIRES_NEW) to avoid issues with nested transactions.
Example:
@Service
public class UserService {
@Transactional
public void createUser(User user) {
userRepository.save(user);
// if a checked exception is thrown here, the transaction will not rollback without rollbackFor
}
@Transactional(rollbackFor = Exception.class)
public void createUserWithRollback(User user) throws Exception {
userRepository.save(user);
throw new Exception("Force rollback");
}
}
Overall, it is important to understand how Spring manages transactions and the limitations imposed by the proxy mechanism.