JPA / JTA / @Transactional Spring annotation

I am reading the transaction management Using Spring framework. In first combination I used Spring + hiberante and used Hibernate's API's to control the transaction (Hibenate API's). Next, I wanted to test using @Transactional annotation, and it did work.

I am getting confused on:

  1. Do JPA , JTA, Hibernate have their "own" way of transaction management. As an example, consider if I use Spring + Hibernate, in that case would u use "JPA" transactions?

    Like we have JTA, is it true to say we can use Spring and JTA to control transactions?

  2. The @Transactional annotation, is that specific to Spring Framework? From what I understood, this annotation is Spring Framework specific. If this is correct, is @Transactional using JPA/JTA to do the transaction control?

I do read online to clear my doubts, however something I don't get direct answer. Any inputs would be great help.


Solution 1:

@Transactional in case of Spring->Hibernate using JPA i.e.

@Transactional Annotations should be placed around all operations that are inseparable.

So lets take example:

We have 2 model's i.e. Country and City. Relational Mapping of Country and City model is like one Country can have multiple Cities so mapping is like,

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

Here Country mapped to multiple cities with fetching them Lazily. So here comes role of @Transactinal when we retrieve Country object from database then we will get all the data of Country object but will not get Set of cities because we are fetching cities LAZILY.

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

When we want to access Set of Cities from country object then we will get null values in that Set because object of Set created only this Set is not initialize with there data to get values of Set we use @Transactional i.e.,

//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();   
}

So basically @Transactional is Service can make multiple call in single transaction without closing connection with end point.

Hope this will helpful to you.