Junior — Middle
How to implement transaction management within a Spring application?
sobes.tech AI
Answer from AI
In Spring, transaction management is usually implemented using the @Transactional annotation. It allows declaratively defining transaction boundaries without explicitly writing code to start, commit, or rollback a transaction.
Example of usage:
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Transactional
public void createUser(User user) {
// database operations
userRepository.save(user);
// if an exception occurs during the process, the transaction will rollback
}
}
Transaction management can also be configured via XML configuration or programmatically using PlatformTransactionManager.
Spring supports different types of transactions (e.g., via JDBC, JPA, Hibernate) and allows configuring transaction behavior (e.g., isolation levels, timeout, rollback on specific exceptions).