简体   繁体   English

@Controller类中的@Transactional方法不被视为事务性的

[英]@Transactional methods in @Controller class are not considred as transactional

I noticed that the following is not working in a class marked as a @Controller : 我注意到以下内容在标记为@Controller的类中不起作用:

@Autowired
SessionFactory sessionFactory;

@ResponseBody
@Transactional
@RequestMapping(method = RequestMethod.GET , value = "/map")

public ArrayList<PhotoDTO> getPhotos(...someParams) {
   Entity result sessionFactory.getCurrentSession()... //do some manipulation

  return result;
}

when I call the URL, I get an error saying that the method is not transactional (although, as you can see, it is marked as one) 当我调用URL时,我得到一个错误,说该方法不是事务性的(尽管如您所见,它被标记为一个)

If I copy this method to a another class called MyService and call it from the controller instead, it works perfectly 如果我将此方法复制到另一个名为MyService的类并从控制器调用它,它就可以完美地工作

Is this some sort of a Spring advice (a conspiracy to make me use more classes more or less)? 这是一种Spring建议(一个让我多或少使用更多课程的阴谋)?

Don't do transactions in your controller. 不要在控制器中进行交易。 Put them in your service layer classes. 将它们放在服务层类中。

Separate your code into model-view-controller. 将代码分成模型 - 视图 - 控制器。

Yes it is a conspiracy. 是的,这是一个阴谋。 It enables to you to share code between controllers/views without repeating code. 它使您能够在不重复代码的情况下在控制器/视图之间共享代码。 And also stops rollbacks of transactions unnecessarily (for exceptions unrelated to the actual transaction). 并且还会不必要地停止事务回滚(对于与实际事务无关的异常)。

It might seem like more code to begin with, but in the long run it is much more manageable and simpler to develop. 它看起来似乎更多的代码,但从长远来看,它更易于管理和开发。

Probably you have two application contexts here: main Spring context loaded by ContextLoaderListener and a child context loaded by DispatcherServlet . 可能你在这里有两个应用程序上下文:由ContextLoaderListener加载的主要Spring上下文和由DispatcherServlet加载的子上下文。 You need to put <tx:annotation-driven /> in the configuration loaded by the child context too. 您还需要在子上下文加载的配置中放置<tx:annotation-driven /> If you show us your web.xml file maybe I can help you more. 如果您向我们展示您的web.xml文件,我可以帮助您。

Anyway, as @NimChimpsky says, is usually not a good practice to manage transactions in your controller layer. 无论如何,正如@NimChimpsky所说,管理控制器层中的事务通常不是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM