@Transactional如果
Spring->Hibernate使用
JPAie
@Transactional注释应放在所有不可分割的操作周围。
让我们举个例子:
我们有2个模型的ie
Country和
City。
Country和
City模型的关系映射就像一个国家可以有多个城市,因此映射就像,
@oneToMany(fetch = FetchType.LAZY, mappedBy="country")private Set<City> cities;
在这里,国家/地区映射到多个城市,并懒洋洋地获取它们。因此,
@Transactinal当我们从数据库中检索Country对象时,我们将获得Country对象的所有数据,但由于获得LAZILY而无法获取城市集,因此将发挥作用。
//Without @Transactionalpublic Country getCountry(){ Country country = countryRepository.getCountry(); //After getting Country Object connection between countryRepository and database is Closed }当我们要从国家对象访问城市集时,我们将在该集合中获得空值,因为仅创建了该集合的Set的对象未使用那里的数据初始化来获取我们使用的Set的值,
@Transactional即,
//with @Transactional@Transactionalpublic 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,Service可以在单个事务中进行多个调用,而无需关闭与端点的连接。
希望这对你有所帮助。



