⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unitofwork.txt

📁 java对象/关系数据库映射工具hibernate和java web 框架struts结合的实例
💻 TXT
字号:
By: steve_molitor ( Stephen Molitor )
RE: [NEWS] Struts-Hibernate 0.01
2003-03-11 13:06 We're also using Struts / Hibernate. We're using the 'Open Session in View' pattern described in the 'design patterns' section of the Hibernate site. We wrote a servlet filter that wraps around every *.do request. It starts a Hibernate transaction / session at the beginning of the request, and closes it at the very end. This keeps the session open for use by JSP's.

We use it in conjunction with the 'Thread Local Session' (we call it a UnitOfWork) pattern. Works fine for us. The UnitOfWork thread-local singleton also provides a good spot to put other 'session' stuff like the user info, for consumption by the business tier. The filter initializes the unit of work (which initializes the Hibernate stuff and user info), and closes/rollback the unit of work at the end. (And the unit of work closes the hibernate transaction / session.) There's an option to cache the unit of work in the session for 'wizards', but we haven't tried that yet.

The filter looks something like this:

UnitOfWork.start(user info from session);
try {
filter.doChain(...);
}
catch (...) {
UnitOfWork.rollback();
}
finally {
UnitOfWork.release();
}

UnitOfWork.start initializes the Hibernate session and starts the transaction. Rollback releases the transaction. Release closes the session. Other wrapper methods to register entities as new, deleted, etc. with Hibernate are provided by UnitOfWork. Also a method to get info about the current user.

Again, UnitOfWork is a 'thread-local' singleton. It looks like a process global singleton, but it's not. It uses the ThreadLocal class internally, and there is actually one instance per thread (request). Assuming the filter has properly intialized the unit of work, business tier code can safely call the static methods on the UnitOfWork wherever appropriate.

If you chain your actions, it's important that the filter check to make sure it only executes once per request. This is accomplished by checking/setting a request attribute at the top of the filter. If it's already there, the filter doesn't re-start or close the unit of work.

Steve

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -