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

By | 07月27日
Advertisement

最近一直有朋友在问,最新版的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;
    }
}

Similar Posts:

  • &amp;lt;转&amp;gt;最新版的SSH框整合(Spring 3.1.1 + Struts 2.3.1.2 + Hibernate 4.1)

    原文地址:http://blog.csdn.net/shibingli/article/details/7296987 Web.xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/j

  • Struts 2 + Spring 2.0 + Hibernate 3.0整合笔记(转)

    原文:http://bbs.bccn.net/thread-239025-1-1.html 1. 添加Spring 2.0的Libraries 选择以下4个jar,并配置到/WEB-INF/lib下 Spring2.0 AOP Libraries Spring2.0 Core Libraries Spring2.0 Persistence Core Libraries Spring2.0 WEb Libraries 同时,将applicationContext.xml配置到WEB/INF下面.

  • SSH+Activiti 整合(Spring 3.1.1 + Struts 2.3.3 + BoneCP 0.7.1 + Hibernate 4.1.4 + Activiti 5.9)

    最近项目要用到工作流,所以考察了一下现在的开源工作流引擎,最终考虑在原SSH框架上整合Activiti 工作流引擎.还是那句话请转载的人注明出处,不要做让人看不起的IT人. 多的不说了,本版只提供配置文件,其它部分文件代码可能参考我写的新版SSH整合一文. applicationContext-common.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://ww

  • 使用Struts的Action来通过Hibernate对数据库进行增、删、改、查四项操作

    前言 经过前面的两篇文章,我相信大家对Hibernate与Structs都有了初步的了解. 在Hibernate开发指南之环境准备中我们说明了开发Hibernate和Struts的工具环境的使用及相关原理,并写了一个简单的Hibernate的小例子. 在Hibernate开发指南之Plugin to Struts中我们对Hibernate的SessionFactory的初始化与Struts结合的方法做了一些探讨,让大家对Struts的Plugin有了一定的理解,并且也仔细的了解了Hibernat

  • 整合SSH在Initializing Spring root WebApplicationContex处卡住

    整合SSH合,启动Tomcat时出现:Initializing Spring root WebApplicationContext卡住的情况,且提示JdbcOdbcDriver.class未发现. 注意:而在控制台下以startup.bat方法却可以启动. 我是这样解决的: 1.进入Debug视图 2.在Breakpoints视图中点Remove all breadpoints

  • MyEclipse整合SSH(Struts+Spring+Hibernate)简单登录范例(一)

    1. 准备 工具:MyEclipse 5.1.0 GA.Tomcat 5.5 环境:Struts1.1.Spring1.2.Hibernate3.1.sqlserver2000 1.1. 新建工程 本范例使用最简单的登录模块来实践SSH的开发,旨在体会和入门SSH技术的整合 操作:[Menu] File/New/Web Project 工程名:login 2. Struts 部分 2.1. 添加 Struts 功能支持 操作:[Menu] MyEclipse/Project Capabiliti

  • spring 3.1.2+struts 2.3.2 + mybatis 3.1.1框架搭建(一)

    源码资源地址:http://download.csdn.net/detail/yangjun19890825/4459130 近来由于工作需要,需要搭建一个新的框架,于是使用最新的SSI搭建了一个测试性框架,能够从数据库中查询数据并输出到JSP页面. struts 2.3.4和spring 3.1.2,由于只初步写了测试代码,使用的也都是老版本的功能,新版的mybatis的功能有了很大改进,使得配置异常简单. 1. mybatis配置文件中,在老版本的ibatis中,如果命名别名,需要使用typ

  • Spring 2.0集成Struts 2.0(一)

    引言 Struts 2在经历了两年漫长的开发后,终于在2007年2月底正式发布,Struts 1.3.8是Struts 1的最终版本,Struts 1从此不再升级.Struts 2和Struts 1差别非常大,几乎是两个完全不同的东西,所以不要指望Struts 1在不经过修改的情况下就可以跑在Struts 2环境下.Struts 2与其说是Struts的升级版本,莫如说是WebWork的升级版本--我们可以通过WebWork开发团队当年宣称并入Struts时所提到的一句话了解到这一点:"WebW

  • Spring4 Spring MVC实战(四)——Spring MVC实现类struts通配符跳转,HMTL、Ajax和EasyUI的交互,405及406错误

    1.通配符跳转 Spring4 Spring MVC实战(一)--读<Spring in action>搭建最简单的MVC. 只是配置了特定了路径.但是想想要做到像struts一样的通配符匹配之后进行跳转,在Spring MVC中,这种就应该看文档.http://docs.spring.io/spring/docs/current/spring-framework-reference/html/原始的api文档找到之后是有URI模板方法的: 我自己能想到的跳转方法也是这样的. 获取参数呢,查下

  • spring、struct、hibernate三大框架整合

    一.运用环境: Myeclipse.jdk1.70.Tomcat7.0.mysql 二.整合思路: 1.把Action交给Spring来管理. 2.把SessionFactory交给Spring来管理. 3.把Session打开与关闭交给Spring来管理. 4.把事务打提,提交.回滚交给Spring来管理. 三.整合: 1.创建web project,名为SSH.并新建一个名为res的source folder,用于存放配置文件. 2.将hibernate引人项目 (1)将Hibernate的

Tags: