JPA / JTA / @Transactional Spring annotation

3
我正在阅读关于使用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来进行事务控制呢?
我确实在网上阅读以消除我的疑虑,但有些问题我没有得到直接的答案。任何意见都将是很好的帮助。

@Transactional注释存在于两个包中:javax.transactionorg.springframework.transaction.annotation.Transactional,因此我猜测有JTA/JPA事务处理和Spring事务处理,或者Spring实现了JPA/JTA事务处理。 - Robert Niestroj
谢谢您的信息。在幕后,“org.springframework.transaction.annotation.Transactional”是Spring自己的事务机制,还是使用JPA或JTA? - CuriousMind
你的上下文配置是什么?你使用哪个事务管理器? - Jakub Kubrynski
请参考我之前提出的问题,其中包含了所有的代码和配置文件:http://stackoverflow.com/questions/26596489/hibernate-spring-4-x-and-transactional-annotation - CuriousMind
1个回答

13

@Transactional 在使用 Spring->HibernateJPA 的情况下,应该放置在所有不可分割操作的周围。

让我们举个例子:

我们有两个模型: CountryCityCountryCity 模型的关系映射是一个国家可以有多个城市,所以映射如下:

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

这里一个国家对应多个城市,我们需要延迟加载它们。因此,在从数据库中检索国家对象时,@Transactional 扮演了重要角色,因为我们可以获取到国家对象的所有数据,但不会得到城市集合,因为我们是 延迟加载 城市。

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

当我们想要从国家对象中访问城市集时,我们会得到空值,因为只创建了Set对象,而没有使用数据初始化该Set以获取Set的值,我们使用@Transactional来获取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是指服务可以在单个事务中进行多次调用,而无需关闭与终点的连接

希望这对你有所帮助。


.size() 是强制性的吗? - La Hai
@LaHai 是的,用于获取数据。 - Harshal Patil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接