我想最小化@Transactional 的范围吗? [英] Do I want to minimize the scope of @Transactional?

查看:22
本文介绍了我想最小化@Transactional 的范围吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定此处的范围"是否正确.

Not sure if 'scope' is the correct term here.

我使用 Spring 进行 JPA 事务管理(下面有一个 Hibernate).我执行数据库事务的方法是私有的,但由于您只能在类或 公共方法

I am using Spring for JPA transaction management (with a Hibernate underneath). My method to preform database transaction is private, but since you can only set @Transactional on a class or on a public method

由于此机制基于代理,因此只会拦截通过代理传入的外部"方法调用.这意味着自调用",即目标对象中的一个方法调用目标对象的其他方法,即使被调用的方法被标记为@Transactional,也不会在运行时导致实际的事务!

Since this mechanism is based on proxies, only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

我已将类的公共入口点设置为@Transactional.

I have set the public entry point of the class as @Transactional.

@Transactional
public void run(parameters) {
    //First non-database method, takes a decent amount of time
    Data data = getData();
    //Call to database
    storeData(data);
}

private storeData(data) {
    em.persist(data);
}

这是不好的做法吗?Spring 是否保持一个开放事务的时间比这里需要的时间长?我正在考虑将 storeData() 方法移动到 DAO 类并将其公开,但作为学术观点,我想知道重构为公开是否会带来任何性能优势.

Is this bad practice? Is Spring keep an open transaction for longer then needed here? I was thinking of move the storeData() method to a DAO class and making it public, but as academic point, I wanted to know if refactoring to public would have any performance benefit.

推荐答案

在您的代码执行与事务上下文交互的操作(在本例中为 storeData() 方法)之前,事务范围没有任何影响.getData() 是非事务性的这一事实不应影响代码的并发性能,因为只有在达到 storeData() 时才会发生任何数据库锁定.

The transaction scope is has no effect until your code does something which interacts with the transaction context, in this case the storeData() method. The fact that getData() is non-transactional should not affect the performance on concurrency of your code, since any database locking will only happen when storeData() is reached.

这篇关于我想最小化@Transactional 的范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆