Skip to content

Instantly share code, notes, and snippets.

@vijayrawatsan
Last active June 1, 2018 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vijayrawatsan/998e7c37794f0a0e451a599bb166a845 to your computer and use it in GitHub Desktop.
Save vijayrawatsan/998e7c37794f0a0e451a599bb166a845 to your computer and use it in GitHub Desktop.
Rollback Examples
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ExceptionService {
public void throwException() throws Exception {
throw new Exception("Throw me!");
}
@Transactional(rollbackFor = Exception.class)
public void throwExceptionTransactional() throws Exception {
throw new Exception("Throw me!");
}
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public void throwExceptionTransactionalRequiresNew() throws Exception {
throw new Exception("Throw me!");
}
@Transactional(rollbackFor = Exception.class, noRollbackFor= IllegalArgumentException.class)
public void throwExceptionTransactionalNoRollbackFor() throws Exception {
throw new IllegalArgumentException("Throw me!");
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private ExceptionService exceptionService;
@Autowired
private UserRepository userRepository;
@Transactional(rollbackFor = Exception.class)
public void createUserEx1(String userName) {
userRepository.save(getUser(userName));
try {
exceptionService.throwException();
} catch (Exception e) {
//caught exception never reaches proxy
}
}
@Transactional(rollbackFor = Exception.class)
public void createUserEx2(String userName) {
userRepository.save(getUser(userName));
try {
exceptionService.throwExceptionTransactional();
} catch (Exception e) {
//caught exception but why is rollback happening?
}
}
@Transactional(rollbackFor = Exception.class)
public void createUserEx3(String userName) {
userRepository.save(getUser(userName));
try {
exceptionService.throwExceptionTransactionalRequiresNew();
} catch (Exception e) {
}
}
@Transactional(rollbackFor = Exception.class, noRollbackFor = IllegalArgumentException.class)
public void createUserEx4(String userName) {
userRepository.save(getUser(userName));
throw new IllegalArgumentException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment