Hibernate Open Session in View: Transaction per Request?

筅森魡賤 提交于 2019-11-29 23:19:47

Your concerns are valid, the solution provided on the wiki page is too simplistic. The transaction should not be managed at the web layer - it should be handled at the service layer.

The correct implementation would open a session and bind it to a thread in the filter. No transaction is started. The session is put in flush mode never - read only mode. A service call would set the session to flush mode auto & start / commit the transaction. Once the service method finishes the session flush mode is reverted back to never.

There is also an option to not open the session in the filter. Each service layer call would open a separate session & transaction - after the service call is done the session is not closed, but registered for deferred close. The session will be closed after the web request processing is complete.

Spring provides OpensessionInViewFilter which works as described above. So ignore the jboss wiki article and just configure the OpensessionInViewFilter - everything will be fine.

SessionFactory.getCurrentSession() - internally creates and assigns the session to a thread local. Each request / thread will have its own session. Once the web request processing is complete the session will be closed. From within your code you just need to use SessionFactory.getCurrentSession() and don't have to close it. The code sample on the jboss wiki page is wrong - it should have a SessionFactory.getCurrentSession().close() in the finally block. Or they might be using JTA transaction and configured hibernate to open/close session in conjunction with the JTA transaction.

It is not a problem if the filter creates a session for every request, because the sessions are coming from a session pool, and they will be reused. From the view of the OS, nothing happens.

A hibernate session is, by the fact, a tcp (or socket/pipe) connection to the database server. The cost of the db conn creation is very dependent from the sql type (postgresql is notably bad in this, altough it is very good in every anything). But it doesn't means really anything, because hibernate reuses the database connections.

The simple hibernate filter solution starts a new transaction on the session for every requests, too. It is transaction from the view of the SQL: it is a "BEGIN" and "COMMIT" query. It is always costly, and this should be reduced.

IMHO a possible solution were, if the transactions were started only at the first query of the current request. Maybe spring has something usable for this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!