简体   繁体   中英

Single transaction per request with Spring MVC and Hibernate

I want to use Spring MVC and 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). 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. Also I want view to support lazy hibernate loading, eg select data in an autocommit mode if html template requests that.

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.

I've learned that OpenSessionInViewInterceptor allows to continue using hibernate session in view, so that probably solves my second requirement. 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.

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. So it should solve both your requirements.

See source

The same is true for OpenEntityManagerInView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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