[英]What is the benefit of using @Transactional in Controller layer on spring MVC application
In an Spring 4 MVC application, i noticed that the @Transactional
annotation was used in Controller layer. 在Spring 4 MVC应用程序中,我注意到
@Transactional
批注在控制器层中使用。 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? 在
@Controller
类中使用@Transactional
什么好处?
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. 当方法使用find或从数据库中获取某些数据时,将使用readOnly = true。 But using readOnly = true, the service layer was able to save the data anyways.
但是使用readOnly = true,服务层仍然可以保存数据。 My application uses Spring 4 + Hibernate 4.2.20.
我的应用程序使用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? 在事务内使用“
readOnly = true
”是否能够将数据保存到数据库?
There is no reason to use the annotation @Transactional in the @Controller. 没有理由在@Controller中使用注释@Transactional。
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.
@Controller不应仅在服务层中意识到MVC逻辑中的数据持久性。
Also Spring recommends not to annotate whole classes only certain methods, this is also a good practice so you can mantain easily your application. 此外,Spring建议不要仅对某些方法注释整个类,这也是一种好习惯,因此您可以轻松维护应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.