我正在使用Spring框架阅读事务管理。首先,我使用Spring + hiberante和Hibernate的API来控制事务(Hibenate )。接下来,我想使用@Transactional注释进行测试,它确实起了作用。
我对以下问题感到困惑:
@Transactional注释,这是特定于Spring的吗?据我所知,这个注释是特定于Spring的。如果这是正确的,@Transactional是否使用JPA/JTA来执行事务控制?我确实在网上阅读,以消除我的疑虑,但有些事情我没有得到直接的回答。任何投入都会有很大帮助。
发布于 2014-10-28 18:05:45
@Transactional在Spring->Hibernate使用JPA的情况下,即:
@Transactional注释应该放在所有不可分离的操作周围。
因此,让我们举个例子:
我们有两个模型,即Country和City。Country和City模型的关系映射就像一个国家可以有多个城市,所以映射就像,
@OneToMany(fetch = FetchType.LAZY, mappedBy="country")
private Set<City> cities;这里的乡村映射到多个城市,懒洋洋地抓取它们。因此,当我们从数据库中检索国家对象时,就会出现@Transactinal的角色,然后我们将获取国家对象的所有数据,但不会得到城市的集合,因为我们正在缓慢地获取城市。
//Without @Transactional
public Country getCountry(){
Country country = countryRepository.getCountry();
//After getting Country Object connection between countryRepository and database is Closed
}当我们想要从国家对象访问城市集合时,我们将在该集合中获得空值,因为只创建这个集合的对象不是用那里的数据初始化来获得我们使用@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基本上是服务,它可以在单个事务中进行多个调用,而不需要与端点关闭连接。
希望这对你有帮助。
https://stackoverflow.com/questions/26611173
复制相似问题