1 16 17 package org.springframework.orm.hibernate.support; 18 19 import net.sf.hibernate.HibernateException; 20 import net.sf.hibernate.Session; 21 import net.sf.hibernate.SessionFactory; 22 23 import org.springframework.dao.DataAccessException; 24 import org.springframework.dao.DataAccessResourceFailureException; 25 import org.springframework.dao.support.DaoSupport; 26 import org.springframework.orm.hibernate.HibernateTemplate; 27 import org.springframework.orm.hibernate.SessionFactoryUtils; 28 29 55 public abstract class HibernateDaoSupport extends DaoSupport { 56 57 private HibernateTemplate hibernateTemplate; 58 59 60 66 public final void setSessionFactory(SessionFactory sessionFactory) { 67 this.hibernateTemplate = createHibernateTemplate(sessionFactory); 68 } 69 70 79 protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) { 80 return new HibernateTemplate(sessionFactory); 81 } 82 83 86 public final SessionFactory getSessionFactory() { 87 return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null); 88 } 89 90 95 public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) { 96 this.hibernateTemplate = hibernateTemplate; 97 } 98 99 109 public final HibernateTemplate getHibernateTemplate() { 110 return this.hibernateTemplate; 111 } 112 113 protected final void checkDaoConfig() { 114 if (this.hibernateTemplate == null) { 115 throw new IllegalArgumentException ("'sessionFactory' or 'hibernateTemplate' is required"); 116 } 117 } 118 119 120 137 protected final Session getSession() 138 throws DataAccessResourceFailureException, IllegalStateException { 139 140 return getSession(this.hibernateTemplate.isAllowCreate()); 141 } 142 143 162 protected final Session getSession(boolean allowCreate) 163 throws DataAccessResourceFailureException, IllegalStateException { 164 165 return (!allowCreate ? 166 SessionFactoryUtils.getSession(getSessionFactory(), false) : 167 SessionFactoryUtils.getSession( 168 getSessionFactory(), 169 this.hibernateTemplate.getEntityInterceptor(), 170 this.hibernateTemplate.getJdbcExceptionTranslator())); 171 } 172 173 186 protected final DataAccessException convertHibernateAccessException(HibernateException ex) { 187 return this.hibernateTemplate.convertHibernateAccessException(ex); 188 } 189 190 198 protected final void releaseSession(Session session) { 199 SessionFactoryUtils.releaseSession(session, getSessionFactory()); 200 } 201 202 } 203 | Popular Tags |