英文:
Why this @Transactional doesn't work with rollback operation
问题
你好,StackOverflow社区!我在使用@Transactional时遇到了问题。在我的场景中,它无法正常工作。
在以下代码块中,我遇到了问题,然后在catch块中抛出了DataIntegrityViolationException异常。
jobLinkRepository.save(jobLink);
在方法顶部,我使用了@Transactional并且指定了rollbackFor,但它不起作用。JobOffer始终会被保存。
我使用了
import org.springframework.transaction.annotation.Transactional;
英文:
Hello StackOverflow community! I have problem with @Transactional. It doesn't work properly in my scenario.
How can I rollback
JobOffer jobOffer = jobOfferRepository.save(JobOffer.builder().id(UUID.randomUUID()).build());
@GetMapping("/loadLinks")
public ResponseEntity<?> loadLinks(){
List<String> allLinks = List.of("https://my-domain-sobs.com/pl/job/mid-dev");
for (String singleLink : allLinks) {
saveLink(singleLink);
}
return ResponseEntity.ok().build();
}
@Transactional(rollbackFor = DataIntegrityViolationException.class)
public void saveLink(String singleLink) {
try{
JobOffer jobOffer = jobOfferRepository.save(JobOffer.builder().id(UUID.randomUUID()).build());
JobLink jobLink = JobLink.builder()
.jobLink(singleLink)
.jobOffer(jobOffer)
.isProcessed(false)
.category("Kotlin")
.id(UUID.randomUUID())
.timeOfAddition(LocalDateTime.now())
.remote(true)
.build();
jobLinkRepository.save(jobLink);
} catch (Exception e){
throw new DataIntegrityViolationException("Exception occured during saving link!");
}
}
Here
jobLinkRepository.save(jobLink);
I am getting exception and after in catch I am throwning new DataIntegrityViolationException. On the top of my method I am using Transactional with rollbackFor but it doesn't work. JobOffer is alwayes saved.
I am using
import org.springframework.transaction.annotation.Transactional;
答案1
得分: 1
事务方法必须在单独的类中。你可以查看这个链接:https://www.baeldung.com/transaction-configuration-with-jpa-and-spring
英文:
Transactional method must be in separate class.
You can check this : https://www.baeldung.com/transaction-configuration-with-jpa-and-spring
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论