为什么这个 @Transactional 注解与回滚操作不起作用

huangapple go评论58阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月31日 21:49:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定