在專案中我們使用DAO這個pattern來封裝資料庫存取層,Hibernate Quickly (Manning)中建議我們可以繼承Spring所提供的HibernateDAOSupport來簡化DAO程式碼,這是很常見的作法。
原本method重複性很高的部份:
可以被簡化為:
以下擷取自Spring原始碼
在execute()最後的finally中,session會被關掉。因此從DAO層的method執行結束後,session就被關掉,因此如果在JSP頁面中存取到某些one-to-many (或其他lazy=true的關聯物件時)就會產生exception:
failed to lazily initialize a collection of ...
因為無法再透過session去抓資料。
通常此時會採用Spring提供的OpenSessionInViewFilter來解決,這個filter會在發出request的時候開啟session直到request結束,因此JSP頁面上仍可以透過這個session來取得因為lazy initialization未取得的資料。
但設定上去後,如果你採用Hibernate 3則會產生另一個問題。
當你呼叫DAO的SaveOrUpdate()資料並沒有存進資料庫,只會顯示一堆select 敘述:
並且產生以下Exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
reference:
1.使用語法高亮度http://sjcywg.blogspot.com/2008/02/syntax-highlighting.html
2.相關問題簡述Lazy Initialization and the DAO pattern with Hibernate and Spring
原本method重複性很高的部份:
public void create(Event event) throws DataAccessLayerException { try { startOperation(); session.save(event); tx.commit(); } catch (HibernateException e) { handleException(e); } finally { HibernateFactory.close(session); } }
可以被簡化為:
public abstract class AbstractSpringDao extends HibernateDaoSupport{ public AbstractSpringDao() { } protected void saveOrUpdate(Object obj) { getHibernateTemplate().saveOrUpdate(obj); } protected void delete(Object obj) { getHibernateTemplate().delete(obj); } ... }都透過Sprgin提供的HibernateTemplate幫我們作掉那些重複的開、關session, transaction動作。
以下擷取自Spring原始碼
package org.springframework.orm.hibernate3; ... public class HibernateTemplate extends HibernateAccessor implements HibernateOperations { ... public Object execute(HibernateCallback action) throws DataAccessException { Session session = (!this.allowCreate ? SessionFactoryUtils.getSession(getSessionFactory(),false) : SessionFactoryUtils.getSession(getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator())); boolean existingTransaction = TransactionSynchronizationManager.hasResource(getSessionFactory()); if (!existingTransaction && getFlushMode() == FLUSH_NEVER) { session.setFlushMode(FlushMode.NEVER); } try { Object result = action.doInHibernate(session); flushIfNecessary(session, existingTransaction); return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (SQLException ex) { throw convertJdbcAccessException(ex); } catch (RuntimeException ex) { // callback code threw application exception throw ex; } finally { SessionFactoryUtils.closeSessionIfNecessary(session, getSessionFactory()); } } ... }
在execute()最後的finally中,session會被關掉。因此從DAO層的method執行結束後,session就被關掉,因此如果在JSP頁面中存取到某些one-to-many (或其他lazy=true的關聯物件時)就會產生exception:
failed to lazily initialize a collection of ...
因為無法再透過session去抓資料。
通常此時會採用Spring提供的OpenSessionInViewFilter來解決,這個filter會在發出request的時候開啟session直到request結束,因此JSP頁面上仍可以透過這個session來取得因為lazy initialization未取得的資料。
但設定上去後,如果你採用Hibernate 3則會產生另一個問題。
當你呼叫DAO的SaveOrUpdate()資料並沒有存進資料庫,只會顯示一堆select 敘述:
Hibernate: select employee_.EMPLOYEE_ID, employee_.DEPARTMENT_NAME as DEPARTMENT2_0_, employee_.DEPARTMENT_NO as DEPARTMENT3_0_, employee_.INAUGURATION_DATE as INAUGURA4_0_, employee_.DISCHARGE_DATE as DISCHARGE5_0_, employee_.PROFESSIONAL_TITLE as PROFESSI6_0_, employee_.JOB_LEVEL as JOB7_0_, employee_.DIRECT_SUPERVISOR as DIRECT8_0_, employee_.PERSONAL_PHOTO as PERSONAL9_0_, employee_.CHINESE_NAME as CHINESE10_0_, ... from EMPLOYEES employee_ where employee_.EMPLOYEE_ID=?
並且產生以下Exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
/** * Get a Session for the SessionFactory that this filter uses. * Note that this just applies in single session mode! * The default implementation delegates to the *SessionFactoryUtils.getSession
method and * sets theSession
's flush mode to "NEVER". *
Can be overridden in subclasses for creating a Session with a * custom entity interceptor or JDBC exception translator. * @param sessionFactory the SessionFactory that this filter uses * @return the Session to use * @throws DataAccessResourceFailureException if the Session could not be created * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.hibernate.FlushMode#NEVER */ protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); FlushMode flushMode = getFlushMode(); if (flushMode != null) { session.setFlushMode(flushMode); } return session; }
reference:
1.使用語法高亮度http://sjcywg.blogspot.com/2008/02/syntax-highlighting.html
2.相關問題簡述Lazy Initialization and the DAO pattern with Hibernate and Spring
留言