Abhishek Ranjan
Abhishek Ranjan

Reputation: 931

Layer to use the @Transactional annotation in Spring Data JPA

I am using Spring Data JPA for my application, which has the following layers:

  1. Service layer with Interfaces and Implements (annotated @service)
  2. CRUD repository layer with Spring Data JPA, together with custom repository implementations
  3. Entity layer

I was wondering where exactly is the correct place to put @Transactional. Currently, I have it in the service layer, where the repositories are being used.

Upvotes: 1

Views: 1653

Answers (2)

Roman C
Roman C

Reputation: 1

The correct place to put @Transactional annotation is any layer if you want to add a transactional behaviour to your code. The code assumed to use a database access. Usually, you can use @Transactional on repositories. But if you need, you can add it on the service layer as well.

See Understanding the Spring Framework's declarative transaction implementation

You can place the @Transactional annotation before an interface definition, a method on an interface, a class definition, or a public method on a class. However, the mere presence of the @Transactional annotation is not enough to activate the transactional behavior. The @Transactional annotation is simply metadata that can be consumed by some runtime infrastructure that is @Transactional-aware and that can use the metadata to configure the appropriate beans with transactional behavior.

Upvotes: 0

user997172
user997172

Reputation:

Transactions belong to Service layer. For example if you have HotelService, then the code would look like this:

@Service("hotelService")
@Transactional
public class HotelServiceImpl implements HotelService {
    @Autowired
    HotelDao hotelDao;

    // The rest of code omited ...
}

Upvotes: 3

Related Questions