Reputation: 1471
In an Spring 4 MVC application, i noticed that the @Transactional
annotation was used in Controller layer. But in many places it was recommended to use within the service layer (service implementation class).
What is the benefit of using @Transactional
in @Controller
class?
Also, i have a service layer implementation class, which updates the data to database, i noticed the usage of Transaction properties as below
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
readOnly = true, was to be used when the method uses find or fetch some data from database. But using readOnly = true, the service layer was able to save the data anyways. My application uses Spring 4 + Hibernate 4.2.20.
Transaction manager used by application
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Using "readOnly = true
" within the transaction will be able to save the data to database?
Upvotes: 1
Views: 1583
Reputation: 1003
There is no reason to use the annotation @Transactional in the @Controller.
There is a simple reason not to do this: best practice. A @Controller should not be aware of data persistence in a MVC logic, only the Service layer.
Also Spring recommends not to annotate whole classes only certain methods, this is also a good practice so you can mantain easily your application.
Upvotes: 3