Spring事务管理 @Transactional行为

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

Spring Transaction Management @Transactional behavior

问题

示例1:

@Service
public class UserService {
    @Transactional(readOnly = true)
    public void invoice() {
        createPdf();
        // 发送电子邮件等操作
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPdf() {
        // ...
    }
}

示例2:

@Service
public class UserService {
    @Autowired
    private InvoiceService invoiceService;
    @Transactional(readOnly = true)
    public void invoice() {
        invoiceService.createPdf();
        // 发送电子邮件等操作
    }
}
@Service
public class InvoiceService {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPdf() {
        // ...
    }
}

谢谢

英文:

I wanted to know how the Spring @Transactional will work for the following Coding scenarios. I am using Spring 4 + Hiberante 5 with Oracle 19C database for this example.

Example 1:

@Service
public class UserService {
    @Transactional(readOnly = true)
    public void invoice() {
        createPdf();
        // send invoice as email, etc.
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPdf() {
        // ...
    }
}

Example 2:

@Service
public class UserService {
    @Autowired
    private InvoiceService invoiceService;
    @Transactional(readOnly = true)
    public void invoice() {
        invoiceService.createPdf();
        // send invoice as email, etc.
    }
}
@Service
public class InvoiceService {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPdf() {
        // ...
    }
}

Thanks

答案1

得分: 1

示例 1:由于您正在从您的服务中调用createPDF方法,在此情况下,@Transactional(REQUIRES_NEW)注解将被有效地“忽略”。不会打开新的事务。

示例 2:由于您正在调用另一个被事务代理包装的服务,您将获得一个“新事务”,因为注解会被尊重。

您还可能希望阅读这篇文章:Spring事务管理:@Transactional深入解析

英文:

Example 1: As you are calling the createPDF method from inside your Service, the @Transactional(REQUIRES_NEW) annotation will effectively be ignored. There will be no new transaction opened.

Example 2: As your are calling another service, which is wrapped in a transactional proxy, you will get a new transaction, as the annotation is respected.

You also might want to read up on this article: Spring Transaction Management: @Transactional In-Depth

huangapple
  • 本文由 发表于 2020年4月8日 05:53:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/61089974.html
匿名

发表评论

匿名网友

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

确定