4javier
4javier

Reputation: 639

Spring Hibernate @Transactional clarifications

I got a lot of confusion about @Transactional annotation.

1) If I use just declarative approach, is it enough to mark my service class/methods as @Transactional, or should I create the configuration beans and properties as shown in this Baeldung article?

2) I need to use even programmatical approach in some situations, to be able to explicitly call flush() at a specific point of my workflow. In this case the former definitions of hibernate configs are mandatory?

Upvotes: 1

Views: 240

Answers (1)

LppEdd
LppEdd

Reputation: 21104

If you're on a Spring Boot project, no, you won't need to explicitly declare the SessionFactory or the PlatformTransactionManager Beans. They'll be auto-configured for you.

Yes, putting the Transactional annotation on your class or method is enough for transactions to take place. Auto-commit should even be turned off automatically (for optimization purposes), in case it's not done at DataSource level.

For the "programmatical" part, you should consider staying on the annotation side. You can play with the transaction propagation strategies to isolate certain operations.


A couple important notes about using the declarative, annotation approach.

Remember to annotate public methods, if possible. Any other method visibility cannot be managed via Java proxies or CGLIB proxies, thus, even though you won't notice it, those methods won't participate in the transaction context. For protected or private methods, you're forced to use AspectJ.

Remember also that when using proxies, self-invocation (& expecting a new transaction) doesn't work.


To use the programmatic approach, you just need to Autowire the TransactionTemplate or PlatformTransactionManager Bean.

The PlatformTransactionManager allows for more customization of the transaction, while TransactionTemplate is more of a utility object (which however can be modeled as needed).

Obviously, don't mix both approaches in the same methods call stack.

Upvotes: 3

Related Questions