日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

hibernate底层dao

發布時間:2024/1/23 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hibernate底层dao 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 IBaseDao.java

package com.hm.eams.basic.common.base;import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map;public interface IBaseDao<T, PK extends Serializable> {/*** 創建一個新的實例對象到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return boolean*/public boolean create(T newInstance) throws Exception;/*** 創建一個新的實例對象到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return 返回 Object 主鍵值* @throws Exception*/public Object createObject(T newInstance) throws Exception;/*** 將一個集合對象更新到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return boolean*/public boolean createAll(Collection<T> newInstance)throws Exception;/** 保存對象 */public boolean creatObjcate(Object obj)throws Exception ;/*** 更新一個實例對象到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return boolean*/public boolean update(T newInstance) throws Exception;/*** @param model T 泛型類,代表實際應用中的POJO* @return boolean 返回布爾類型變量* @throws Exception*/public boolean delete(T model) throws Exception;/*** 根據ID和類型從數據庫刪除數據* @param id PK 主鍵* @param T 泛型類,代表實際應用中的POJO* @return T* @throws Exception*/public T delete(PK id, Class<T> T) throws Exception;/*** 從數據庫刪除實例* @param sql String* @return boolean*/public boolean deleteBySQL(String sql) throws Exception;/*** 從數據庫刪除實例* @param condition String 刪除操作的條件* @return boolean*/public boolean delete(String condition) throws Exception;/*** 根據主鍵查找實例對象* @param id PK 主鍵* @return T*/public T findById(PK id) throws Exception;/*** 根據SQL查找實例對象* @param sql String* @return T*/public T findBySQL(String sql) throws Exception;/*** 查找所有實例對象* @return List*/public List<T> findAll() throws Exception;/*** 根據SQL查找對象列表* @param sql String* @return List*/public List<T> findAllBySQL(String sql) throws Exception;/*** 根據SQL查找對象列表* * @param SQL sql語句* @param values 0個或多個參數* @return* @throws Exception*/public List<T> findAllBySQLAndParameter(String SQL, Object... values) throws Exception;/*** 使用HQL查詢返回列表* @param hql HQL語句* @param Object... values 多個條件參數* @return* @throws Exception*/public List<T> findListByHQL(String hql, Object... values) throws Exception;/*** 使用HQL查詢返回列表* @param hql HQL語句* @param List<Object> values 多個條件參數* @return* @throws Exception*/public List<T> findListByHQL(String hql, List<Object> values) throws Exception;/** 使用HQL查詢 分頁導出*/public List<T> findByHqlPage(final String hql, final Integer page,final Integer pageSize) throws Exception ;/*** 查找分頁信息,該方法只針對單表操作有效* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param condition String 查詢條件* @return PageInfo 分頁信息對象*/public PageInfo findPageInfo(int currentPage, int pageSize, String condition)throws Exception;/*** 分頁顯示實例對象信息列表,該方法只針對單表操作有效* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param condition String 查詢條件* @return List 實例對象列表*/public List<T> findPageList(int currentPage, int pageSize, String condition) throws Exception;/*** 使用hql查找分頁信息* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param hql String hql查詢語句* @param values Object 條件值對象集合* @return PageInfo 分頁信息對象*/public PageInfo findPageInfo(int currentPage, int pageSize, String hql, Object...values) throws Exception;/*** 使用hql分頁顯示實例對象信息列表* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param hql String hql查詢語句* @param values Object 條件值對象集合* @return List 實例對象列表*/public List<T> findPageList(int currentPage, int pageSize, String hql, Object...values) throws Exception;/*** 查找分頁信息,該方法對所有操作有效* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param SQL String SQL語句* @return PageInfo 分頁信息對象*/public PageInfo findPageInfoBySQL(int currentPage, int pageSize, String SQL, Object...values)throws Exception;/*** 分頁顯示實例對象信息列表,該方法對所有操作有效* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param SQL String SQL語句* @return List 實例對象列表*/public List<T> findPageListBySQL(int currentPage, int pageSize, String SQL, Object...values)throws Exception;/*** 分頁顯示實例對象信息列表,該方法對所有操作有效* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param SQL String SQL語句* @return List 實例對象列表*/public List<T> findPageListBySQLWithOrder(int currentPage, int pageSize, String SQL, Object...values)throws Exception;/*** 獲得查詢總數* @param sql* @return* @throws Exception*/public Integer findDataCount(String sql) throws Exception;public List<Map> findToMapBySQL(final String sql) ;public void execInsert(final String insertSql,final Object...params);}


2 BaseDaoImpl.java

package com.hm.eams.basic.common.base;import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.transform.Transformers; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.util.Assert;import com.hm.basic.repository.BaseHibernateRepository; import com.hm.util.HibernateUtil; import com.hm.util.StringUtil;public abstract class BaseDaoImpl<T, PK extends Serializable> extends BaseHibernateRepository implements IBaseDao<T, PK> {private Log log = LogFactory.getLog(BaseDaoImpl.class);/**泛型類,代表實際應用中的POJO*/private Class<T> type;public BaseDaoImpl() {this.type = (Class<T>) ((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0];}/*** 創建一個新的實例對象到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return boolean*/public boolean create(T newInstance)throws Exception {boolean bFlag = false;getHibernateTemplate().save(newInstance);bFlag = true;return bFlag;}/*** 將一個集合對象更新到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return boolean*/public boolean createAll(Collection<T> newInstance)throws Exception {boolean bFlag = false;getHibernateTemplate().saveOrUpdateAll(newInstance);bFlag = true;return bFlag;}/** 保存對象的 */public boolean creatObjcate(Object obj)throws Exception {boolean bFlag = false;getHibernateTemplate().saveOrUpdate(obj);bFlag = true;return bFlag;}/**** Description:創建一個新的實例對象到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return 返回 Object 主鍵值* @throws Exception*/public Object createObject(T newInstance) throws Exception{Object t = getHibernateTemplate().save(newInstance);return t;}/*** 更新一個實例對象到數據庫* @param newInstance T 泛型類,即實際應用中的POJO* @return boolean*/public boolean update(T newInstance)throws Exception {boolean bFlag = false;getHibernateTemplate().update(newInstance);bFlag = true;return bFlag;}/*** 刪除實例* @param model T 泛型類,代表實際應用中的POJO* @return boolean 返回布爾類型變量* @throws Exception*/public boolean delete(T model) throws Exception {boolean bFlag = false;getHibernateTemplate().delete(model);bFlag = true;return bFlag;}/*** 根據ID和類型從數據庫刪除數據* @param id PK 主鍵* @param T 泛型類,代表實際應用中的POJO* @return T* @throws Exception*/@SuppressWarnings("unchecked")public T delete(PK id, Class<T> T) throws Exception {T obj = null;obj = (T)getHibernateTemplate().get(T, id);getHibernateTemplate().delete(obj);return obj;}/*** 從數據庫刪除實例* @param SQL String* @return boolean*/public boolean deleteBySQL(final String SQL)throws Exception {boolean bFlag = false;this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {session.createSQLQuery(SQL).executeUpdate();return null;} });bFlag = true;return bFlag;}/*** 從數據庫刪除實例* @param condition String 刪除操作的條件* @return boolean*/public boolean delete(String condition)throws Exception {boolean bFlag = false;String SQL = "delete from " + this.type.getName() + " " +condition;this.getHibernateTemplate().bulkUpdate(SQL);bFlag = true;return bFlag;}/*** 根據主鍵查找實例對象* @param id PK 主鍵* @return T* @throws Exception */@SuppressWarnings("unchecked")public T findById(PK id) throws Exception {return (T) getHibernateTemplate().get(type, id);}/*** 根據SQL查找實例對象* @param SQL String* @return T*/@SuppressWarnings("unchecked")public T findBySQL(final String SQL) throws Exception{return (T)this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query =session.createSQLQuery(SQL).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); Iterator iter = query.list().iterator();Object object = null;while (iter.hasNext()) {try {object = type.newInstance();HibernateUtil.copyProperty(object, (Map) iter.next());} catch (java.lang.InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}return (T) object; } });}/*** 查找所有實例對象* @return List*/@SuppressWarnings("unchecked")public List<T> findAll() throws Exception {String HQL = "from " + this.type.getSimpleName();try {return (List<T>) getHibernateTemplate().find(HQL);} catch (DataAccessException ex) {ex.printStackTrace();return null;} catch (Exception ex) {ex.printStackTrace();log.error("findAll:"+ex.toString());return null;}}/*** 根據SQL查找對象列表* @param SQL String* @return List*/@SuppressWarnings("unchecked")public List<T> findAllBySQL(final String SQL) throws Exception{if(!StringUtil.isNullOrBlank(SQL)){return (List<T>)this.getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query =session.createSQLQuery(SQL).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);Iterator iter = query.list().iterator();List list = new ArrayList();while (iter.hasNext()) {Object object=null;try {object = type.newInstance();HibernateUtil.copyProperty(object, (Map) iter.next());list.add(object);} catch (java.lang.InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}return list;} });}else{return this.findAll();}}/*** 根據SQL查找對象列表* * @param SQL* @param values 參數0...** @return* @throws Exception*/public List<T> findAllBySQLAndParameter(String SQL, Object... values) throws Exception {Query query = createSQLQuery(SQL, values).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);Iterator iter = query.list().iterator();List list = new ArrayList();while (iter.hasNext()) {Object object = null;try {object = type.newInstance();HibernateUtil.copyProperty(object, (Map) iter.next());list.add(object);} catch (java.lang.InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}return list;}/*** 使用HQL查詢返回列表* @param hql HQL語句* @param values 多個條件參數* @return* @throws Exception*/public List<T> findListByHQL(String hql, Object... values) throws Exception { if(!StringUtil.isNullOrBlank(hql)){if(values!=null && values.length>0){return createQuery(hql,values).list();}else{return createQuery(hql).list();} }else{return this.findAll();}}/*** 使用HQL查詢返回列表* @param hql HQL語句* @param values 多個條件參數* @return* @throws Exception*/public List<T> findListByHQL(String hql, List<Object> values) throws Exception {Object[] objs = null;List<T> list = new ArrayList(); if(values!=null && values.size()>0){objs = new Object[values.size()];for(int i=0;i<values.size();i++){objs[i] = values.get(i);}}Query query=createQuery(hql,objs);if(query!=null) {list = query.list();}return list;}/*** 根據查詢函數與參數列表創建Query對象,后續可進行更多處理,輔助函數* @param queryString* @param values* @return*/protected Query createQuery(String queryString, Object... values) {Assert.hasText(queryString);Query queryObject = getSession().createQuery(queryString);if (values != null) {for (int i=0; i<values.length; i++) {queryObject.setParameter(i, values[i]);}}return queryObject; }protected Query createSQLQuery(String queryString, Object... values) {Assert.hasText(queryString);Query queryObject = getSession().createSQLQuery(queryString);if (values != null) {for (int i=0; i<values.length; i++) {queryObject.setParameter(i, values[i]);}}return queryObject; }public List<T> findByHqlPage(final String hql, final Integer page,final Integer pageSize) throws Exception {// TODO Auto-generated method stubreturn this.getHibernateTemplate().executeFind(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query query=session.createQuery(hql);if(page!=null && pageSize!=null){query.setFirstResult((page-1)*pageSize).setMaxResults(pageSize);}return ( List<T>) query.list();}});}/*** 查找分頁信息,該方法只針對單表操作有效* @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param condition String 查詢條件* @return PageInfo 分頁信息對象*/public PageInfo findPageInfo(final int currentPage, final int pageSize, final String condition) throws Exception {return (PageInfo)this.getHibernateTemplate().execute(new HibernateCallback() {@SuppressWarnings("unchecked")public Object doInHibernate(Session session) throws HibernateException, SQLException { PageInfo pageInfo = new PageInfo();String SQL = "select count(*) as amount from "+ type.getSimpleName();if (condition != null)SQL += condition; Query query = session.createQuery(SQL);List<Long> list = (List<Long>) query.list();pageInfo.setCurrentPage(currentPage);pageInfo.setPageSize(pageSize);int count = 0;Object cv = "0";if(list!=null && list.size()>0){cv = list.get(0);if(cv==null){cv = "0";}count = ((Long) list.get(0)).intValue();}pageInfo.setTotalCount(count);// 總頁數double pagenum = Double.valueOf(cv.toString())/Double.valueOf(String.valueOf(pageSize)); Double dub = new Double(Math.ceil(pagenum)); int totalPage = dub.intValue();if(totalPage<=1){pageInfo.setCurrentPage(1);}else{pageInfo.setCurrentPage(currentPage);}pageInfo.setTotalPage(totalPage);return pageInfo; }}); }/*** 分頁顯示實例對象信息列表,該方法只針對單表操作有效* @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param condition String 查詢條件* @return List 實例對象列表* @throws Exception */@SuppressWarnings("unchecked")public List<T> findPageList(final int currentPage, final int pageSize, final String condition) throws Exception { return (List<T>)this.getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {String HQL = " from "+ type.getSimpleName();if (condition != null)HQL += condition;Query query = session.createQuery(HQL);query.setFirstResult((currentPage - 1) * pageSize);query.setMaxResults(pageSize);return (List<T>) query.list(); } });}/*** 使用hql查找分頁信息* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param hql String hql查詢語句* @param values Object 條件值對象集合* @return PageInfo 分頁信息對象*/public PageInfo findPageInfo(final int currentPage, final int pageSize, final String hql, final Object...values) throws Exception{return (PageInfo)this.getHibernateTemplate().execute(new HibernateCallback() {@SuppressWarnings("unchecked")public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query = createQuery(hql, values);List<Long> list = (List<Long>) query.list();PageInfo pageInfo = new PageInfo();pageInfo.setCurrentPage(currentPage);pageInfo.setPageSize(pageSize);int count = 0 ;Object cv = "0";if(list!=null && list.size()>0){cv = list.get(0);if(cv==null){cv = "0";}count = ((Long)list.get(0)).intValue();}pageInfo.setTotalCount(count);// 總頁數double pagenum = Double.valueOf(cv.toString())/Double.valueOf(String.valueOf(pageSize)); Double dub = new Double(Math.ceil(pagenum)); int totalPage = dub.intValue();if(totalPage<=1){pageInfo.setCurrentPage(1);}else{pageInfo.setCurrentPage(currentPage);}pageInfo.setTotalPage(totalPage);return pageInfo; }}); }/*** 使用hql分頁顯示實例對象信息列表* * @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param hql String hql查詢語句* @param values Object 條件值對象集合* @return List 實例對象列表*/@SuppressWarnings("unchecked")public List<T> findPageList(final int currentPage, final int pageSize, final String hql, final Object...values) throws Exception{return (List<T>)this.getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query = createQuery(hql, values);query.setFirstResult((currentPage - 1) * pageSize);query.setMaxResults(pageSize);return (List<T>) query.list(); } });}/*** 查找分頁信息,該方法對所有操作有效* @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param sql String SQL語句* @return PageInfo 分頁信息對象*/public PageInfo findPageInfoBySQL(final int currentPage, final int pageSize, final String sql, final Object...values)throws Exception {return (PageInfo)this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = createSQLQuery(sql, values);List list = query.list();Object cv = "0";if(list!=null && list.size()>0){cv = list.get(0);if(cv==null){cv = "0";}}PageInfo pageInfo = new PageInfo();// 總頁數double pagenum = Double.valueOf(cv.toString())/Double.valueOf(String.valueOf(pageSize)); Double dub = new Double(Math.ceil(pagenum)); int totalPage = dub.intValue();if(totalPage<=1){pageInfo.setCurrentPage(1);}else{pageInfo.setCurrentPage(currentPage);} pageInfo.setPageSize(pageSize);pageInfo.setTotalCount(Integer.valueOf(cv.toString()));pageInfo.setTotalPage(totalPage);return pageInfo; }});}/*** 分頁顯示實例對象信息列表,該方法對所有操作有效* @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param sql String SQL語句* @return List 實例對象列表*/@SuppressWarnings("unchecked")public List<T> findPageListBySQL(final int currentPage, final int pageSize, final String sql, final Object...values) throws Exception{return this.getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query = createSQLQuery(sql, values);query.setMaxResults(pageSize);query.setFirstResult((currentPage - 1) * pageSize);query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);Iterator iter = query.list().iterator();List list = new ArrayList();while (iter.hasNext()) {Object object;try {object = type.newInstance();HibernateUtil.copyProperty(object, (Map) iter.next());list.add(object);} catch (java.lang.InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}return list;} });}/*** 分頁顯示實例對象信息列表,該方法對所有操作有效* @param currentPage int 當前頁碼* @param pageSize int 每頁顯示的記錄數* @param sql String SQL語句* @return List 實例對象列表*/@SuppressWarnings("unchecked")public List<T> findPageListBySQLWithOrder(final int currentPage, final int pageSize, final String sql, final Object...values) throws Exception{return this.getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query = createSQLQuery(sql, values);query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);Iterator iter = query.list().iterator();List list = new ArrayList();while (iter.hasNext()) {Object object;try {object = type.newInstance();HibernateUtil.copyProperty(object, (Map) iter.next());list.add(object);} catch (java.lang.InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}return list;} });}/*** 獲得翻頁面的SQL語句* * @param sql SQL語句* @param currentPage 當前頁* @param pageNum 頁的數量* @return*/private static String makePageSQL(String sql, int currentPage, int pageSize) {int startPos = (currentPage - 1) * pageSize ;int endPos = currentPage * pageSize;// 先按查詢條件查詢出從0到頁未的記錄.然后再取出從頁開始到頁未的記錄StringBuffer sqlBuffer = new StringBuffer();sqlBuffer.append("select * from (select row_.*, rownum rownum_ from (");sqlBuffer.append(sql);sqlBuffer.append(") row_) where rownum_ >"+ startPos +" and rownum_<="+ endPos);return sqlBuffer.toString();}public Integer findDataCount(final String sql) throws Exception {return (Integer)this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Query query = session.createSQLQuery(sql);List list = query.list();Object cv = "0";if(list!=null && list.size()>0){if(list.get(0)!=null)cv = list.get(0); }return Integer.valueOf(cv.toString());}});}/*** @author tcx* @param sql* @return*/@SuppressWarnings("unchecked")public List<Map> findToMapBySQL(final String sql) {return (List<Map>) this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException,SQLException {Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);return (List<Map>) query.list();}});}public void execInsert(final String insertSql,final Object...params){this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException,SQLException {Query query = session.createSQLQuery(insertSql);for(int i=0;i<params.length;i++){query.setParameter(i, params[i]);}query.executeUpdate();return null;}});} }


3 BaseHibernateRepository.java

package com.hm.basic.repository;import javax.annotation.Resource;import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.support.DaoSupport; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.SessionFactoryUtils;public abstract class BaseHibernateRepository extends DaoSupport {private HibernateTemplate hibernateTemplate;/*** Set the Hibernate SessionFactory to be used by this DAO. Will* automatically create a HibernateTemplate for the given SessionFactory.* * @see #createHibernateTemplate* @see #setHibernateTemplate*/@Autowired@Resource(name="sessionFactory")public final void setSessionFactory(SessionFactory sessionFactory) {if (this.hibernateTemplate == null|| sessionFactory != this.hibernateTemplate.getSessionFactory()) {this.hibernateTemplate = createHibernateTemplate(sessionFactory);}}/*** Create a HibernateTemplate for the given SessionFactory. Only invoked if* populating the DAO with a SessionFactory reference!* <p>* Can be overridden in subclasses to provide a HibernateTemplate instance* with different configuration, or a custom HibernateTemplate subclass.* * @param sessionFactory* the Hibernate SessionFactory to create a HibernateTemplate for* @return the new HibernateTemplate instance* @see #setSessionFactory*/protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {return new HibernateTemplate(sessionFactory);}/*** Return the Hibernate SessionFactory used by this DAO.*/public final SessionFactory getSessionFactory() {return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);}/*** Set the HibernateTemplate for this DAO explicitly, as an alternative to* specifying a SessionFactory.* * @see #setSessionFactory*/public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;}/*** Return the HibernateTemplate for this DAO, pre-initialized with the* SessionFactory or set explicitly.* <p>* <b>Note: The returned HibernateTemplate is a shared instance.</b> You* may introspect its configuration, but not modify the configuration (other* than from within an {@link #initDao} implementation). Consider creating a* custom HibernateTemplate instance via* <code>new HibernateTemplate(getSessionFactory())</code>, in which case* you're allowed to customize the settings on the resulting instance.*/public final HibernateTemplate getHibernateTemplate() {return this.hibernateTemplate;}protected final void checkDaoConfig() {if (this.hibernateTemplate == null) {throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");}}/*** Obtain a Hibernate Session, either from the current transaction or a new* one. The latter is only allowed if the* {@link org.springframework.orm.hibernate3.HibernateTemplate#setAllowCreate "allowCreate"}* setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is* "true".* <p>* <b>Note that this is not meant to be invoked from HibernateTemplate code* but rather just in plain Hibernate code.</b> Either rely on a* thread-bound Session or use it in combination with* {@link #releaseSession}.* <p>* In general, it is recommended to use HibernateTemplate, either with the* provided convenience operations or with a custom HibernateCallback that* provides you with a Session to work on. HibernateTemplate will care for* all resource management and for proper exception conversion.* * @return the Hibernate Session* @throws DataAccessResourceFailureException* if the Session couldn't be created* @throws IllegalStateException* if no thread-bound Session found and allowCreate=false* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory,* boolean)*/protected final Session getSession()throws DataAccessResourceFailureException, IllegalStateException {return getSession(this.hibernateTemplate.isAllowCreate());}/*** Obtain a Hibernate Session, either from the current transaction or a new* one. The latter is only allowed if "allowCreate" is true.* <p>* <b>Note that this is not meant to be invoked from HibernateTemplate code* but rather just in plain Hibernate code.</b> Either rely on a* thread-bound Session or use it in combination with* {@link #releaseSession}.* <p>* In general, it is recommended to use* {@link #getHibernateTemplate() HibernateTemplate}, either with the* provided convenience operations or with a custom* {@link org.springframework.orm.hibernate3.HibernateCallback} that* provides you with a Session to work on. HibernateTemplate will care for* all resource management and for proper exception conversion.* * @param allowCreate* if a non-transactional Session should be created when no* transactional Session can be found for the current thread* @return the Hibernate Session* @throws DataAccessResourceFailureException* if the Session couldn't be created* @throws IllegalStateException* if no thread-bound Session found and allowCreate=false* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory,* boolean)*/protected final Session getSession(boolean allowCreate)throws DataAccessResourceFailureException, IllegalStateException {return (!allowCreate ? SessionFactoryUtils.getSession(getSessionFactory(), false) : SessionFactoryUtils.getSession(getSessionFactory(), this.hibernateTemplate.getEntityInterceptor(), this.hibernateTemplate.getJdbcExceptionTranslator()));}/*** Convert the given HibernateException to an appropriate exception from the* <code>org.springframework.dao</code> hierarchy. Will automatically* detect wrapped SQLExceptions and convert them accordingly.* <p>* Delegates to the* {@link org.springframework.orm.hibernate3.HibernateTemplate#convertHibernateAccessException}* method of this DAO's HibernateTemplate.* <p>* Typically used in plain Hibernate code, in combination with* {@link #getSession} and {@link #releaseSession}.* * @param ex* HibernateException that occured* @return the corresponding DataAccessException instance* @see org.springframework.orm.hibernate3.SessionFactoryUtils#convertHibernateAccessException*/protected final DataAccessException convertHibernateAccessException(HibernateException ex) {return this.hibernateTemplate.convertHibernateAccessException(ex);}/*** Close the given Hibernate Session, created via this DAO's SessionFactory,* if it isn't bound to the thread (i.e. isn't a transactional Session).* <p>* Typically used in plain Hibernate code, in combination with* {@link #getSession} and {@link #convertHibernateAccessException}.* * @param session* the Session to close* @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession*/protected final void releaseSession(Session session) {SessionFactoryUtils.releaseSession(session, getSessionFactory());}}


?

?

?

?

總結

以上是生活随笔為你收集整理的hibernate底层dao的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。