I'm currently working with some legacy code whereby transactions are rolled manually. Consider the following (example for illustrative purposes only, ignore syntax/design issues):
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
private PlatformTransactionManager transactionManager;
private DefaultTransactionDefinition txDefRequired = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
private DefaultTransactionDefinition txDefRequiresNew new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
void createPosts(Map<String, String> posts){
TransactionStatus status = transactionManager.getTransaction(txDefRequiresNew)
try {
// posts Map is made up for username:posttext key pair
for (Map.Entry<String, String> entry : posts.entrySet()) {
// Construct online post
createPost(entry.getKey(), entry.getValue());
}
transactionManager.commit(status);
} finally {
if (!status.isCompleted()) {
transactionManager.rollback(status);
}
}
}
void createPost(String username, String text){
TransactionStatus status = transactionManager.getTransaction(txDefRequired)
// Construct online post
OnlinePost p = new OnlinePost(text);
User u = resolveUser(username);
p.setUser(u);
transactionManager.commit(status); // flush the session
}
User resolveUser(String username){
TransactionStatus status = transactionManager.getTransaction(txDefRequired)
User u = getUser(username);
if(u == null)
createUser(username);
return u;
transactionManager.commit(status); // flush the session
}
Would it be correct to say that in this particular flow, tx.commit() within the called methods, such as resolveUser(), will only serve to flush the session (flush-mode = auto) and return a new persistent entity with an artificial primary key generated and assigned to it so that you can use it later on in the same transaction?