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