JPA/JTA/@Transactional Spring注释

Cur*_*ind 3 spring annotations hibernate jpa spring-mvc

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

我对此感到困惑:

  1. JPA,JTA,Hibernate是否有自己的"事务管理"方式.举个例子,考虑一下我是否使用Spring + Hibernate,那么你会使用"JPA"事务吗?

    就像我们有JTA一样,我们可以使用Spring和JTA来控制交易吗?

  2. @Transactional注释,是特定于Spring框架是什么?根据我的理解,这个注释是特定于Spring Framework的.如果这是正确的,@Transactional使用JPA/JTA进行事务控制?

我在网上阅读以清除我的怀疑,但是我没有直接回答.任何输入都会有很大的帮助.

Har*_*til 13

@TransactionalSpring->Hibernate使用JPAie的情况下

@Transactional 应该围绕所有不可分割的操作放置注释.

让我们举个例子:

我们有2个模型即CountryCity.关系映射CountryCity模型就像一个国家可以有多个城市所以映射就像,

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

在这里,国家映射到多个城市,并将其取出.因此,@Transactinal当我们从数据库中检索Country对象时,我们将获得Country对象的所有数据但是不会获得城市集,因为我们正在获取城市LAZILY.

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

当我们想要从country对象访问City of Cities时,我们将在该Set中获取null值,因为Set的对象只创建了这个Set没有初始化那里有数据来获取我们使用的Set的值@Transactionalie,

//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();   
}
Run Code Online (Sandbox Code Playgroud)

所以基本上@Transactional服务可以使单个事务多个呼叫,而不关闭与终点连接.

希望这对你有所帮助.