简体   繁体   English

Spring MVC 和 Hibernate 每个请求的单个事务

[英]Single transaction per request with Spring MVC and Hibernate

I want to use Spring MVC and Hibernate.我想使用 Spring MVC 和 Hibernate。 I don't want to use service layer or @Transactional attribute on all controller methods (or, rather, I want Spring to treat them all as transactional).我不想在所有控制器方法上使用服务层或@Transactional属性(或者,我希望 Spring 将它们全部视为事务性的)。 So I want to start transaction when controller method starts to work with database and commit transaction when controller method returns ViewAndModel or rollback transaction if any error occured.所以我想在控制器方法开始使用数据库时启动事务,并在控制器方法返回 ViewAndModel 或回滚事务时提交事务,如果发生任何错误。 Also I want view to support lazy hibernate loading, eg select data in an autocommit mode if html template requests that.我还希望视图支持延迟休眠加载,例如,如果 html 模板请求,则在自动提交模式下选择数据。

I'm aware that best practice involves creating a separate service layer with @Transactional attribute, but my application won't benefit from that additional complexity and I want to simplify code as much as possible.我知道最佳实践涉及使用@Transactional属性创建一个单独的服务层,但我的应用程序不会从这种额外的复杂性中受益,我想尽可能地简化代码。

I've learned that OpenSessionInViewInterceptor allows to continue using hibernate session in view, so that probably solves my second requirement.我了解到OpenSessionInViewInterceptor允许在视图中继续使用休眠会话,因此这可能解决了我的第二个要求。 But how do I make all controller methods transactional?但是如何使所有控制器方法都具有事务性?

Ideally I want an easy way to opt-out from this behaviour if I ever would need that.理想情况下,如果我需要,我想要一种简单的方法来选择退出这种行为。 Eg all methods are transactional, yet I can apply something like @NonTransactional and manage transactions more granularly.例如,所有方法都是事务性的,但我可以应用 @NonTransactional 之类的方法并更精细地管理事务。

Actually OpenSessionInViewInterceptor will open a session (and implicitly a transaction) before any of your controller code starts and close it just before the http request is completed.实际上OpenSessionInViewInterceptor将在您的任何控制器代码开始之前打开一个会话(并隐式地进行一个事务),并在 http 请求完成之前关闭它。 So it should solve both your requirements.所以它应该可以解决你的两个要求。

See source查看来源

The same is true for OpenEntityManagerInView . OpenEntityManagerInView也是如此。

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

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