Spring 3.1.1 + Struts 2.3.1.2 + Hibernate 4.1 整合(SSH) – JAVA編程語言程序開發技術文章

最近一直有朋友在問,最新版的Spring、Struts、Hibernate整合老是有問題,昨晚大概看瞭一下。從Hibernate 4 開始,本身已經很好的實現瞭數據庫事務模塊,而Spring也把Hibernate4之後的HibernateDaoSupport去掉瞭,Spring建議使用官方的HibernateAPI進行操作。這樣一來,以前習慣使用HibernateDaoSupport來操作的人來說剛剛開始可能有些不習慣。我跟據官方的說明,大概的整合一下。
 
 
 
現在把主要的代碼和配置貼出來,供大傢參考,其它配置文件和代碼和以前沒有什麼大變化,直接就能用,主要就是Dao。
 
 
        之前發過的幾篇文章都被人轉瞭N千次,但是我發現被轉的文章都沒有標明原作者,有的還把自己的大名寫上去瞭。用我同事的一句說:“沒文化真可怕!” 那些轉載不留名的朋友,你們不羞愧嗎?做人要厚道,轉載請留名!
 
 
 
Web.xml
 
 
[html]
 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     id="WebApp_ID" version="3.0">
     <display-name>Eriloan_com</display-name>
     <session-config>
         <session-timeout>30</session-timeout>
     </session-config>
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:/spring-config/applicationContext-*.xml</param-value>
     </context-param>
     <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
     <listener>
         <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
     </listener>
     <listener>
         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
     </listener>
     <listener>
         <listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class>
     </listener>
     <filter>
         <filter-name>encodingFilter</filter-name>
         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
         <init-param>
             <param-name>encoding</param-name>
             <param-value>UTF-8</param-value>
         </init-param>
         <init-param>
             <param-name>forceEncoding</param-name>
             <param-value>true</param-value>
         </init-param>
     </filter>
     <filter-mapping>
         <filter-name>encodingFilter</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
     <filter>
         <filter-name>struts-cleanup</filter-name>
         <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>struts-cleanup</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
     <filter>
         <filter-name>struts2</filter-name>
         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>struts2</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
     <filter>
         <filter-name>openSessionInViewFilter</filter-name>
         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
         <init-param>
             <param-name>sessionFactoryBeanName</param-name>
             <param-value>sessionFactory</param-value>
         </init-param>
         <init-param>
             <param-name>singleSession</param-name>
             <param-value>true</param-value>
         </init-param>
         <init-param>
             <param-name>flushMode</param-name>
             <param-value>AUTO</param-value>
         </init-param>
     </filter>
     <filter-mapping>
         <filter-name>openSessionInViewFilter</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
 
     <welcome-file-list>
         <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>
     <error-page>
         <error-code>404</error-code>
         <location>/WEB-INF/errorPage/404.jsp</location>
     </error-page>
     <error-page>
         <error-code>500</error-code>
         <location>/WEB-INF/errorPage/500.jsp</location>
     </error-page>
 </web-app>
 
Spring配置文件(applicationContext-common.xml):
 
[html]
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
     xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/jee
      http://www.springframework.org/schema/jee/spring-jee.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util.xsd
      http://www.springframework.org/schema/tool
      http://www.springframework.org/schema/tool/spring-tool.xsd"
     default-lazy-init="true" default-autowire="byName">
 
     <bean id="propertyConfigurer"
         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="locations">
             <list>
                 <value>classpath:/dataBaseInfo.properties</value>
             </list>
         </property>
     </bean>
 
     <!– <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" 
         p:jndiName="java:comp/env/jdbc/MySSH" /> –>
 
     <!– BoneCP –>
     <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
         p:driverClass="${jdbc.driver}" p:jdbcUrl="${jdbc.url}" p:username="${jdbc.username}"
         p:password="${jdbc.password}" p:idleConnectionTestPeriodInMinutes="${idleConnectionTestPeriodInMinutes}"
         p:idleMaxAgeInMinutes="${idleMaxAgeInMinutes}"
         p:maxConnectionsPerPartition="${maxConnectionsPerPartition}"
         p:minConnectionsPerPartition="${minConnectionsPerPartition}"
         p:partitionCount="${partitionCount}" p:acquireIncrement="${acquireIncrement}"
         p:statementsCacheSize="${statementsCacheSize}"
         p:disableConnectionTracking="${disableConnectionTracking}"
         p:releaseHelperThreads="${releaseHelperThreads}" destroy-method="close" />
     
     <bean id="sessionFactory"
         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
         p:dataSource-ref="dataSource">
 
         <property name="mappingDirectoryLocations">
             <list>
                 <value>classpath:/com/eriloan/web/test/bo/</value>
             </list>
         </property>
 
         <property name="hibernateProperties">
             <props>
                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                 <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
                 <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
                 <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
                 <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
                 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                 <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
                 <prop key="hibernate.order_updates">${hibernate.order_updates}</prop>
                 <prop key="hibernate.query.factory_class">${hibernate.query.factory_class}</prop>
                 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                 <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
 <!–                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> –>
             </props>
         </property>
     </bean>
 
     <bean id="transactionManager"
         class="org.springframework.orm.hibernate4.HibernateTransactionManager" />
 
     <bean id="transactionInterceptor"
         class="org.springframework.transaction.interceptor.TransactionInterceptor"
         p:transactionManager-ref="transactionManager">
         <property name="transactionAttributes">
             <props>
                 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
                 <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
                 <prop key="select*">PROPAGATION_REQUIRED,readOnly</prop>
                 <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>             
                 <prop key="sync*">PROPAGATION_REQUIRED</prop>
                 <prop key="finish*">PROPAGATION_REQUIRED</prop>
                 <prop key="add*">PROPAGATION_REQUIRED</prop>
                 <prop key="insert*">PROPAGATION_REQUIRED</prop>
                 <prop key="edit*">PROPAGATION_REQUIRED</prop>
                 <prop key="update*">PROPAGATION_REQUIRED</prop>
                 <prop key="save*">PROPAGATION_REQUIRED</prop>
                 <prop key="remove*">PROPAGATION_REQUIRED</prop>
                 <prop key="delete*">PROPAGATION_REQUIRED</prop>
                 <prop key="*">PROPAGATION_REQUIRED,-java.lang.Exception</prop>
             </props>
         </property>
     </bean>
 
     <bean id="ProxyCreator"
         class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
         p:beanNames="*Service,*ServiceImpl" p:interceptorNames="transactionInterceptor" />
 
     <!– 數據庫操作Bean –>
     <bean id="dao" class="dao.DaoImpl" scope="singleton" />
 
     <!–Service 原始Bean –>
     <bean id="baseService" class="service.BaseServiceImpl" scope="singleton" />
     
     <!–Action 原始Bean –>
     <bean id="baseAction" class="action.BaseAction" scope="prototype" />
 
 </beans>
 
SpringBean配置文件(applicationContext-beans.xml):
 
[html]
 <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
     xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/jee
      http://www.springframework.org/schema/jee/spring-jee.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util.xsd
      http://www.springframework.org/schema/tool
      http://www.springframework.org/schema/tool/spring-tool.xsd"
     default-lazy-init="true" default-autowire="byName" >
 
     <!– Test Bean By Eric Shi –>
     <bean id="testService"
         class="com.eriloan.web.test.service.impl.TestServiceImpl"
         scope="singleton" />
     <bean id="testAction" class="com.eriloan.web.test.action.TestAction"
         scope="prototype" />
 
     
 </beans>
 
Struts2 配置主配置文件(struts.xml):
 
[html]
 <?xml version="1.0" encoding="UTF-8" ?>
 
 <!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
     "http://struts.apache.org/dtds/struts-2.3.dtd">
 
 <struts>
     <include file="struts-default.xml" />
 
     <!– 默認的配置包–>
     <package name="defaultPackage" extends="struts-default,json-default,jfreechart-default,spring-default">
 
 
         <global-results>
             <!– 公用返回頁面–>
             <result name="error" type="dispatcher">/errorPage/index.jsp</result>
             <result name="login" type="dispatcher">/login.jsp</result>
             <result name="defaultLogin" type="redirect">/quitSys.jsp</result>
             <result name="loginOut" type="redirect">/loginAction!loginPage.action
             </result>
             <result name="ajaxJson" type="json">
                 <param name="contentType">text/html</param>
                 <param name="root">ajax_json</param>
             </result>
             <!– 異常返回頁面–>
             <result name="actionException" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
             </result>
             <result name="serviceException" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
             </result>
             <result name="daoException" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
             </result>
             <result name="exception" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
             </result>
         </global-results>
         <!– 異常處理–>
         <global-exception-mappings>
             <!– Action 層異常處理–>
             <exception-mapping result="actionException"
                 exception="system.exception.ActionException" />
             <!– Service 層異常處理–>
             <exception-mapping result="serviceException"
                 exception="system.exception.ServiceException" />
             <!– DAO 層異常處理–>
             <exception-mapping result="daoException"
                 exception="system.exception.DaoException" />
             <!– 未知的系統異常,後臺沒有對此信息進行歸類–>
             <exception-mapping result="exception" exception="java.lang.Exception" />
         </global-exception-mappings>
     </package>
     
     <!–前臺調用靜態方法–>
     <!– <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant> –>
     
     <!– Test by Eric –>
     <include file="/struts-config/test/test_Struts.xml" />
 
 </struts>
 
Struts 2業務配置文件(test_Struts.xml):
 
[html]
 <?xml version="1.0" encoding="UTF-8" ?>
 
 <!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
     "http://struts.apache.org/dtds/struts-2.3.dtd">
 
 <struts>
     <package name="testPackage" extends="defaultPackage">
         <action name="testAction" class="testAction">
             <!–Test Path–>
            <result name="gotoTestPage" type="dispatcher">/page/test/testPage.jsp</result>        
         </action>
     </package>
 </struts>
 
Struts2 屬性配置文件(struts.properties):
 
[html]
 struts.devMode=true
 struts.action.extension=action
 struts.objectFactory = spring
 struts.objectFactory.spring.autoWire = name
 struts.objectFactory.spring.useClassCache = true
 struts.objectFactory.spring.autoWire.alwaysRespect = true
 struts.configuration.xml.reload=true
 struts.i18n.encoding = utf-8
 struts.tag.altSyntax=true
 struts.custom.i18n.resources=Eriloan_Text
 struts.locale=zh_CN
 struts.ui.theme = simple 
 struts.ognl.allowStaticMethodAccess=true
 struts.multipart.maxSize=10000000000
 #struts2.sslplugin.httpPort=8080
 #struts2.sslplugin.httpsPort=8443
 #struts2.sslplugin.annotations=true
 #struts.multipart.parser=cos
 #struts.multipart.parser=pell
 struts.multipart.parser=jakarta
 struts.multipart.saveDir=tempUpload
 
數據庫配置文件:
 
[html]
 #MySQL配置
 hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
 #hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
 #hibernate.dialect=org.hibernate.dialect.MySQLDialect
 jdbcjdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
 jdbc.driver=com.mysql.jdbc.Driver
 jdbc.username=root
 jdbc.password=root
 
 hibernate.show_sql=true
 hibernate.format_sql=false
 hibernate.use_sql_comments=false
 hibernate.cache.use_second_level_cache=false
 hibernate.cache.use_query_cache=false
 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
 hibernate.hbm2ddl.auto=update
 hibernate.order_updates=true
 hibernate.jdbc.batch_size=30
 hibernate.jdbc.fetch_size=100
 hibernate.max_fetch_depth=2
 
 #hibernate4.0事務的模式
 #1:org.hibernate.context.internal.ThreadLocalSessionContext – 當前session通過當前執行的線程來跟蹤和界定。
 #2:org.hibernate.context.internal.JTASessionContext – 當前session根據JTA來跟蹤和界定。這和以前的僅支持JTA的方法是完全一樣的。
 #3:org.hibernate.context.internal.ManagedSessionContext
 #4:org.springframework.orm.hibernate4.SpringSessionContext – spring的事務管理。
 hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
 #Hibernate4.0的查詢翻譯器:
 hibernate.query.factory_class=org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
 #Hibernate3.0的查詢翻譯器:
 #hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
 #Hibernate2.1的查詢翻譯器
 #hibernate.query.factory_class=org.hibernate.hql.classic.ClassicQueryTranslatorFactory
 
 
 #Connection Pooling
 
 #acquireIncrement: 當連接池中的連接耗盡的時候一次同時獲取的連接數。Default: 3
 #idleConnectionTestPeriod:檢查數據庫連接池中控線連接的間隔時間,單位是分,默認值:240,如果要取消則設置為0
 #idleMaxAge:連接池中未使用的鏈接最大存活時間,單位是分,默認值:60,如果要永遠存活設置為0
 #maxConnectionsPerPartition:每個分區最大的連接數
 #minConnectionsPerPartition:每個分區最小的連接數
 #partitionCount:分區數,默認值2,最小1,推薦3-4,視應用而定
 #acquireIncrement:每次去拿數據庫連接的時候一次性要拿幾個,默認值:2
 #statementsCacheSize:緩存prepared statements的大小,默認值:0
 #releaseHelperThreads:每個分區釋放鏈接助理進程的數量,默認值:3,除非你的一個數據庫連接的時間內做瞭很多工作,不然過多的助理進程會影響你的性能 
 
 minPoolSize=5
 maxPoolSize=20
 maxIdleTime=1800
 idleConnectionTestPeriodInMinutes=240
 maxStatements=0
 idleMaxAgeInMinutes=240
 maxConnectionsPerPartition=30
 minConnectionsPerPartition=5
 partitionCount=3
 acquireIncrement=5
 statementsCacheSize=50
 releaseHelperThreads=2
 disableConnectionTracking=true
 
 
 
Dao代碼:
 
 
[java]
 package dao;
 
 import java.io.Serializable;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
 import org.apache.log4j.Logger;
 import org.hibernate.Query;
 import org.hibernate.SessionFactory;
 
 import system.exception.DaoException;
 import bo.PageEntity;
 import dao.hqlProvider.IHqlProviderSet;
 
 /**
  *
  * <p>Copyright: All Rights Reserved</p>
  * <p>Company: 北京新線科技發展有限公司http://www.NewLineTech.cn</p>
  * <p>Description: Dao實現類</p>
  *
  * @author:Eric
  */
 public class DaoImpl implements IDao{
     protected Logger log = Logger.getLogger(DaoImpl.class);
 
     /**
      * Hibernate Session 工廠
      */
     private SessionFactory sessionFactory;
 
     /**      * 

     * <br/>Description:根據傳入的實體向數據庫添加一條記錄
     * 
     * @author Eric
     * @param obj
     * @throws DaoException
     */ 
    public void addObject(Object obj) throws DaoException{ 
        log.debug("BaseDao addObject object " + obj); 
        try{ 
            sessionFactory.getCurrentSession().save(obj); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象添加記錄異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:強制刷新Hibernate緩存提交數據更改操作
     * 
     * @author Eric
     * @return
     * @version V1.0
     */ 
    public void dbFlush() throws DaoException{ 
        log.debug("BaseDao addObject dbFlush"); 
        try{ 
            sessionFactory.getCurrentSession().flush(); 
        }catch(Exception e){ 
            throw new DaoException("刷新緩存失敗,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入的實體向數據庫添加一條記錄,返回插入記錄的主鍵
     * 
     * @author Eric
     * @param obj
     * @return
     * @throws DaoException
     */ 
    public String addObjectPK(Object obj) throws DaoException{ 
        log.debug("BaseDao addObjectPK object " + obj); 
        String id = null; 
        try{ 
            id = (String) sessionFactory.getCurrentSession().save(obj); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象添加記錄異常,請聯系管理員!",e); 
        } 
        return id; 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入的實體從數據庫刪除一條記錄
     * 
     * @author Eric
     * @param obj
     * @throws DaoException
     */ 
    public void deleteObject(Object obj) throws DaoException{ 
        log.debug("BaseDao deleteObject object " + obj); 
        try{ 
            sessionFactory.getCurrentSession().delete(obj); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象刪除記錄異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入的實體與ID從數據庫刪除一條記錄
     * 
     * @author Eric
     * @param cls
     * @param id
     * @throws DaoException
     */ 
    @SuppressWarnings({"rawtypes"}) 
    public void deleteObject(Class cls,Serializable id) throws DaoException{ 
        log.debug("BaseDao deleteObject Class " + cls.getName() + " id " + id.toString()); 
        try{ 
            this.deleteObject(sessionFactory.getCurrentSession().get(cls,id)); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象與ID刪除記錄異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入的實體修改數據庫中一條記錄
     * 
     * @author Eric
     * @param obj
     * @throws DaoException
     */ 
    public void updateObject(Object obj) throws DaoException{ 
        log.debug("BaseDao updateObject object " + obj); 
        try{ 
            sessionFactory.getCurrentSession().update(obj); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象更新記錄異常,請聯系管理員!"); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入的實體修改數據庫中一條記錄,返回更新記錄的主鍵
     * 
     * @author Eric
     * @param obj
     * @return
     * @throws DaoException
     */ 
    public String updateObjectPK(Object obj) throws DaoException{ 
        log.debug("BaseDao updateObjectPK object " + obj); 
        String id = null; 
        try{ 
            id = this.addObjectPK(obj); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象更新記錄異常,請聯系管理員!",e); 
        } 
        return id; 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入的實體添加或修改數據庫中一條記錄
     * 
     * @author Eric
     * @param obj
     * @throws DaoException
     */ 
    public void addOrUpdate(Object obj) throws DaoException{ 
        log.debug("BaseDao updateObjectPK object " + obj); 
        try{ 
            sessionFactory.getCurrentSession().saveOrUpdate(obj); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入對象保存數據異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據ID返回一個對象
     * 
     * @author Eric
     * @param cls
     * @param id
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings({"rawtypes"}) 
    public Object findObjectById(Class cls,Serializable id) throws DaoException{ 
        log.debug("BaseDao findObjectById Class " + cls.getName() + " id " + id.toString()); 
        Object obj = null; 
        try{ 
            obj = sessionFactory.getCurrentSession().get(cls,id); 
        }catch(Exception e){ 
            throw new DaoException("根據對象及ID查詢記錄異常,請聯系管理員!",e); 
        } 
        return obj; 
    } 
 
    /**
     * 
     * <br/>Description:根據實體返回一個集合
     * 
     * @author Eric
     * @param cls
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings({"rawtypes"}) 
    public List findAllData(Class cls) throws DaoException{ 
        log.debug("BaseDao findAllData Class " + cls.getName()); 
        List list = null; 
        try{ 
            list = sessionFactory.getCurrentSession().createQuery(" from " + cls.getName() + "").list(); 
        }catch(Exception e){ 
            throw new DaoException("根據對象查詢記錄異常,請聯系管理員!",e); 
        } 
        return list; 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入HQL語句返回一個集合(供DAO使用)
     * 
     * @author Eric
     * @param hql
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings("rawtypes") 
    public List findHQLObject(String hql) throws DaoException{ 
        try{ 
            return sessionFactory.getCurrentSession().createQuery(hql).list(); 
        }catch(Exception e){ 
            throw new DaoException("根據傳入條件語句查詢記錄異常,請聯系管理員!"); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:按HQL提供者別名與條件查詢集合
     * 
     * @author Eric
     * @param hqlProviderSet
     * @param queryName
     * @param paramMap
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings("rawtypes") 
    public List findListByHqlName(IHqlProviderSet hqlProviderSet,String queryName,Map paramMap) throws DaoException{ 
        String hql; 
        try{ 
            hql = hqlProviderSet.getHqlByQryName(queryName); 
            Query query = sessionFactory.getCurrentSession().createQuery(hql); 
            if(paramMap != null){ 
                hqlArgs(paramMap,query); 
            } 
 
            return query.list(); 
        }catch(Exception e){ 
            throw new DaoException("按HQL提供者別名與條件查詢集合異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:按HQL提供者別名、條件、分頁信息查詢集合
     * 
     * @author Eric
     * @param hqlProviderSet
     * @param queryName
     * @param paramMap
     * @param page
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings("rawtypes") 
    public List findListByHqlName(IHqlProviderSet hqlProviderSet,String queryName,Map paramMap,PageEntity page) throws DaoException{ 
        String hql; 
        try{ 
            hql = hqlProviderSet.getHqlByQryName(queryName); 
 
            Query query = sessionFactory.getCurrentSession().createQuery(hql); 
 
            if(paramMap != null){ 
                hqlArgs(paramMap,query); 
            } 
 
            query.setFirstResult((page.getPageNo() – 1) * page.getPageSize()); 
            query.setMaxResults(page.getPageSize()); 
 
            return query.list(); 
        }catch(Exception e){ 
            throw new DaoException("按HQL提供者別名、條件、分頁信息查詢集合異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據傳入實體對象返回總記錄數
     * 
     * @author Eric
     * @param cls
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings("rawtypes") 
    public int findIntRowCountByHqlName(Class cls) throws DaoException{ 
        try{ 
            Query query = sessionFactory.getCurrentSession().createQuery(" select count(c.id) from " + cls.getName() + " c "); 
            List list = query.list(); 
            int rowCount = ((Number) list.get(0)).intValue(); 
            return rowCount; 
        }catch(Exception e){ 
            throw new DaoException("查詢記錄總數異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:根據HQL提供者別名與條件查詢記錄總數
     * 
     * @author Eric
     * @param hqlProviderSet
     * @param queryName
     * @param paramMap
     * @return
     * @throws DaoException
     */ 
    @SuppressWarnings("rawtypes") 
    public int findIntRowCountByHqlName(IHqlProviderSet hqlProviderSet,String queryName,Map paramMap) throws DaoException{ 
        String hql; 
        try{ 
            hql = hqlProviderSet.getHqlByQryName(queryName); 
            Query query = sessionFactory.getCurrentSession().createQuery(hql); 
            if(paramMap != null){ 
                hqlArgs(paramMap,query); 
            } 
            List list = query.list(); 
            int rowCount = ((Number) list.get(0)).intValue(); 
            return rowCount; 
        }catch(Exception e){ 
            throw new DaoException("執行帶參數的查詢記錄總數異常,請聯系管理員!",e); 
        } 
    } 
 
    /**
     * 
     * <br/>Description:為Hibernate查詢設置參數
     * 
     * @author Eric
     * @param argsMap
     * @param query
     */ 
    @SuppressWarnings("rawtypes") 
    public void hqlArgs(Map argsMap,Query query){ 
        Iterator itKey = argsMap.keySet().iterator(); 
        while(itKey.hasNext()){ 
            String key = (String) itKey.next(); 
            @SuppressWarnings("unused") 
            Object obj = argsMap.get(key); 
            if(argsMap.get(key) instanceof List){ 
                query.setParameterList(key,(List) argsMap.get(key)); 
            }else{ 
                query.setParameter(key,argsMap.get(key)); 
            } 
        } 
    } 
 
    public SessionFactory getSessionFactory(){ 
        return sessionFactory; 
    } 
 
    public void setSessionFactory(SessionFactory sessionFactory){ 
        this.sessionFactory = sessionFactory; 
    } 

Jar包:

 摘自 史丙利的博客(Eric Shi)

發佈留言