JPA / JTA / @Transactional Spring注释

时间:2014-10-28 14:41:25

标签: spring hibernate spring-mvc jpa annotations

我正在阅读使用Spring框架的事务管理。在第一个组合中,我使用Spring + hiberante并使用Hibernate的API来控制事务(Hibenate API)。接下来,我想使用@Transactional注释进行测试,它确实有效。

我对此感到困惑:

  1. JPA,JTA,Hibernate都有自己的“交易方式” 管理。作为一个例子,考虑我是否使用Spring + Hibernate 那个案子你会用“JPA”交易吗?

    就像我们有JTA一样,说我们可以使用Spring和JTA是真的 控制交易?

  2. @Transactional注释是特定于Spring的 框架?据我所知,这个注释是Spring 特定于框架。如果这是正确的,@Transactional使用 JPA / JTA做交易控制吗?

  3. 我在线阅读以清除疑虑,但是我没有得到直接回答。任何输入都会有很大帮助。

1 个答案:

答案 0 :(得分:13)

如果@Transactional使用Spring->Hibernate,则

JPA

@Transactional注释应围绕所有不可分割的操作。

让我们举个例子:

我们有2个模型,即CountryCityCountryCity模型的关系映射就像一个国家可以拥有多个城市,因此映射就像,

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

此处国家/地区映射到多个城市,并通过Lazily获取它们。 因此,当我们从数据库中检索Country对象时,我们将获得@Transactinal的角色,然后我们将获得Country对象的所有数据但不会获得城市集,因为我们正在获取城市LAZILY。

//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 服务可以在单个交易中进行多次调用而不关闭与终点的连接

希望这对你有所帮助。