您应该将@Transactional放在DAO类和/或它们的方法中,还是更好地注释使用DAO对象调用的服务类?或者对两个“层”都加注释有意义吗?


当前回答

@Transactional注释应该放在所有不可分割的操作周围。 使用@Transactional可以自动处理事务传播。在这种情况下,如果当前方法调用了另一个方法,那么该方法将可以选择加入正在进行的事务。

让我们举个例子:

我们有两个模型,即国家和城市。国家和城市模型的关系映射就像一个国家可以有多个城市,所以映射就像,

@OneToMany(fetch = FetchType.LAZY, mappedBy="country")
private Set<City> cities;

在这里国家映射到多个城市,获取他们懒惰。这里是@Transactinal的作用当我们从数据库中检索Country对象时,我们会得到Country对象的所有数据,但不会得到城市的集合,因为我们是懒洋洋地获取城市。

//Without @Transactional
public Country getCountry(){
   Country country = countryRepository.getCountry();
   //After getting Country Object connection between countryRepository and database is Closed 
}

当我们想要从国家对象访问Set of Cities时,我们将在该Set中获得空值,因为只有该Set创建的对象没有初始化该Set的数据来获取Set的值,我们使用@Transactional,即,

//with @Transactional
@Transactional
public Country getCountry(){
   Country country = countryRepository.getCountry();
   //below when we initialize cities using object country so that directly communicate with database and retrieve all cities from database this happens just because of @Transactinal
   Object object = country.getCities().size();   
}

所以基本上@Transactional is Service可以在单个事务中进行多个调用,而无需关闭与端点的连接。

其他回答

传统Spring体系结构的正确答案是将事务语义放在服务类上,原因其他人已经描述过了。

An emerging trend in Spring is toward domain-driven design (DDD). Spring Roo exemplifies the trend nicely. The idea is to make the domain object POJOs a lot richer than they are on typical Spring architectures (usually they are anemic), and in particular to put transaction and persistence semantics on the domain objects themselves. In cases where all that's needed is simple CRUD operations, the web controllers operate directly on the domain object POJOs (they're functioning as entities in this context), and there's no service tier. In cases where there's some kind of coordination needed between domain objects, you can have a service bean handle that, with @Transaction as per tradition. You can set the transaction propagation on the domain objects to something like REQUIRED so that the domain objects use any existing transactions, such as transactions that were started at the service bean.

从技术上讲,这种技术使用了AspectJ和<context:spring-configured />。Roo使用AspectJ类型间定义将实体语义(事务和持久性)与领域对象(基本上是字段和业务方法)分离开来。

通常,应该将事务放在服务层。

但是正如前面所述,操作的原子性告诉我们哪里需要注释。因此,如果你使用像Hibernate这样的框架,其中一个“save/update/delete/…”一个对象上的“modify”操作有可能修改几个表中的几行(因为通过对象图的级联),当然在这个特定的DAO方法上也应该有事务管理。

我更喜欢在方法级的服务层上使用@Transactional。

首先,让我们定义一下在什么地方使用事务?

我认为正确的答案是——当我们需要确保动作序列将作为一个原子操作一起完成时,或者即使其中一个动作失败,也不会进行任何更改。

将业务逻辑放入服务中是众所周知的实践。因此,服务方法可能包含必须作为单个逻辑工作单元执行的不同操作。如果是,那么这种方法必须被标记为事务性的。当然,并不是每个方法都需要这样的限制,所以您不需要将整个服务标记为事务性的。

更重要的是,不要忘记考虑@Transactional可能会降低方法性能。 为了了解全局,您必须了解事务隔离级别。了解这一点可以帮助您避免在不必要的地方使用@Transactional。

此外,Spring建议只在具体的类上使用注释,而不是在接口上使用。

http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html