`

Spring 3.1.1 + Struts 2.3.1.2 + Hibernate 4.1 整合(SSH)

 
阅读更多
最近一直有朋友在问,最新版的Spring、Struts、Hibernate整合老是有问题,昨晚大概看了一下。从Hibernate 4 开始,本身已经很好的实现了数据库事务模块,而Spring也把Hibernate4之后的HibernateDaoSupport去掉了,Spring建议使用官方的HibernateAPI进行操作。这样一来,以前习惯使用HibernateDaoSupport来操作的人来说刚刚开始可能有些不习惯。我跟据官方的说明,大概的整合一下。



现在把主要的代码和配置贴出来,供大家参考,其它配置文件和代码和以前没有什么大变化,直接就能用,主要就是Dao。

Web.xml


<?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):


<?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):



<?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):



<?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):


<?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):



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


数据库配置文件:


#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代码:



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; 
    } 
} 

分享到:
评论

相关推荐

    spring3.1+struts2.3+hibernate4.1搭建

    以下是使用Spring 3.1.1、Struts2.3.1.21和Hibernate 4.1搭建整合应用的详细步骤。 一、Struts2.3.1.21的搭建 1. 引入Struts2的核心库:在项目中添加struts-2.3.1.21的JAR包,这是实现Struts2功能的基础。 2. 配置...

    整合SSH_Struts2.3.4.1+Spring3.1.1+Hibernate4.1.6

    压缩包中包含的"整合SSH_Struts2.3.4.1+Spring3.1.1+Hibernate4.1.6+mysql.doc"文档很可能是详细的操作指南,包括每一步的配置细节、代码示例和常见问题解答。而"SSH.rar"文件则包含了整个项目的源码,包括Maven或...

    spring3.1.1+struts2.1+hibernate4.14 整合 myeclipse2014+sqlserver2014简单的增加demo

    这个整合项目是基于Spring 3.1.1、Struts 2.1和Hibernate 4.14,且与MyEclipse 2014集成,使用SQL Server 2014作为数据库。这个"SSHPrj"压缩包提供了一个简单的增删改查(CRUD)的示例,帮助开发者理解如何将这些...

    Struts2.3.4 + Spring3.1.1 + Hibernate4.1.0集成

    Struts2.3.4、Spring3.1.1和Hibernate4.1.0是三个在Java开发领域中广泛使用的开源框架,它们分别是MVC框架、依赖注入框架和对象关系映射工具。这个集成项目(prj_mgr_04_ssh2)的目标是将这三个框架协同工作,以构建...

    SSH+EXTJS4。doc

    在本文档中,Struts2版本为2.3.4,需要配置`struts2-spring-plugin-2.3.4.1.jar`以整合Spring框架。 2. **Spring**:Spring是一个全面的后端应用程序框架,提供了依赖注入(DI)和面向切面编程(AOP)等核心功能,...

    SSH.rar_mysql ssh_ssh mysql_ssh+mysql

    在“ssh_mysql”和“ssh+mysql”的标签中,可以看出SSH可能被用来安全地访问和管理运行MySQL的远程服务器。 在这个“SSH.rar”压缩包中,可能包含的是一个整合了这些技术的示例项目或者教程。SSH可能被用作连接和...

    SSH整合包下载,亲测可用。

    SSH整合包是一个包含Struts2、Spring3.1.1和Hibernate4.1这三大主流Java Web框架的集合,主要用于简化开发过程,提高开发效率。这个整合包已经经过测试,确保了其可用性,这对于开发者来说是一个宝贵的资源,能够...

    毕业设计-基于SSH网上商城的设计与实现.pdf

    4.1 Spring框架实现................................................................................... 23 4.1.1 依赖注入....................................................................................

    java web技术开发大全(最全最新)

    《Java Web开发技术大全:JSP+Servlet+Struts+Hibernate+Spring+Ajax》特别介绍了Struts 2对AjAX的支持,还重点剖析了SSH框架的整合开发,并给出了两个综合案例来展示整合SSH框架开发Web应用。 和已经出版的同类图书...

    java web开发技术大全

    《Java Web开发技术大全:JSP+Servlet+Struts+Hibernate+Spring+Ajax》特别介绍了Struts 2对AjAX的支持,还重点剖析了SSH框架的整合开发,并给出了两个综合案例来展示整合SSH框架开发Web应用。 和已经出版的同类图书...

    基于jsp+ssh的滑雪场管理系统源码数据库论文.doc

    该系统利用Java技术作为后端开发语言,SSH(Struts2、Hibernate、Spring)框架进行业务逻辑处理,MySQL作为数据存储,MyEclipse作为集成开发环境,Tomcat作为应用服务器,构建了一个完整的、可扩展的系统架构。...

    Java学习笔记-个人整理的

    {1.8.1.2}Preincrement}{28}{subsubsection.1.8.1.2} {1.8.1.3}复合赋值运算}{28}{subsubsection.1.8.1.3} {1.8.2}逻辑运算}{29}{subsection.1.8.2} {1.8.3}条件运算符}{29}{subsection.1.8.3} {1.8.4}移位...

    OA办公自动化系统分析报告

    本项目采用Struts2+Spring+Hibernate(SSH)框架,结合MySQL数据库,确保了技术上的可行性。 1.2 需求分析 1.2.1 目标分析:系统的目标是提供一个全面的平台,涵盖用户权限管理、人员管理、日常管理、考勤管理、...

    Java Web编程宝典-十年典藏版.pdf.part2(共2个)

    主要包括Java Web开发环境、JSP语法、JSP内置对象、Java Bean技术、Servlet技术、EL与JSTL标签库、数据库应用开发、初识Struts2基础、揭密Struts2高级技术、Hib锄劬e技术入门、Hibernate高级应用、Spring核心之IoC、...

    BBS需求分析说明书

    SSH框架,由Struts、Hibernate和Spring组成,是Java Web开发中常用的三大开源框架,因其强大的功能和高效的性能,被广泛应用于构建企业级应用。 1.3 **参考资料** 本需求分析参考了多种BBS系统的成功案例,结合用户...

    工程硕士学位论文 基于Android+HTML5的移动Web项目高效开发探究

    SSH 为 Struts+Spring+Hibernate的一个集成框架,是目前较流行的一种Web应用程序开源框架。其中使用Struts作为系统的整体基础架构,负责MVC的分离,在Struts框架的模型部分,控制业务跳转,利用Hibernate框架对持久...

Global site tag (gtag.js) - Google Analytics