Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-17 06:43:22 Viewed : 821
Examples of declarative and programmatic transaction management in Spring Boot:
Certainly! Here are examples of declarative and programmatic transaction management in Spring Boot:
@Transactional
):java@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void createUser(User user) {
// Perform some business logic
userRepository.save(user);
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public User getUserById(Long userId) {
// Perform some business logic
return userRepository.findById(userId).orElse(null);
}
}
In this example, the createUser
and getUserById
methods of the UserService
class are annotated with @Transactional
. The transactional behavior is defined by the presence of these annotations. The createUser
method starts a transaction, and if an exception occurs, the transaction will be rolled back. The getUserById
method is marked as read-only, indicating that it doesnt modify the data and can optimize the transaction accordingly.
java@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PlatformTransactionManager transactionManager;
public void createUser(User user) {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
try {
// Perform some business logic
userRepository.save(user);
transactionManager.commit(transactionStatus);
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
}
}
public User getUserById(Long userId) {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
try {
// Perform some business logic
User user = userRepository.findById(userId).orElse(null);
transactionManager.commit(transactionStatus);
return user;
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
throw e;
}
}
}
In this example, the createUser
and getUserById
methods of the UserService
class use programmatic transaction management. The PlatformTransactionManager
is autowired into the class, and the methods explicitly manage the transactions using the transaction manager. The getTransaction
method starts a transaction, and the commit
method is called to commit the transaction. If an exception occurs, the rollback
method is called to roll back the transaction.
These examples demonstrate the usage of both declarative and programmatic transaction management in Spring Boot. While declarative transaction management with @Transactional
is more commonly used and recommended, programmatic transaction management provides fine-grained control over transaction handling when needed.