<转>最新版的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/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
5 id="WebApp_ID" version="3.0">
6 <display-name>Eriloan_com</display-name>
7 <session-config>
8 <session-timeout>30</session-timeout>
9 </session-config>
10 <context-param>
11 <param-name>contextConfigLocation</param-name>
12 <param-value>classpath:/spring-config/applicationContext-*.xml</param-value>
13 </context-param>
14 <listener>
15 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
16 </listener>
17 <listener>
18 <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
19 </listener>
20 <listener>
21 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
22 </listener>
23 <listener>
24 <listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class>
25 </listener>
26 <filter>
27 <filter-name>encodingFilter</filter-name>
28 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
29 <init-param>
30 <param-name>encoding</param-name>
31 <param-value>UTF-8</param-value>
32 </init-param>
33 <init-param>
34 <param-name>forceEncoding</param-name>
35 <param-value>true</param-value>
36 </init-param>
37 </filter>
38 <filter-mapping>
39 <filter-name>encodingFilter</filter-name>
40 <url-pattern>/*</url-pattern>
41 </filter-mapping>
42 <filter>
43 <filter-name>struts-cleanup</filter-name>
44 <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
45 </filter>
46 <filter-mapping>
47 <filter-name>struts-cleanup</filter-name>
48 <url-pattern>/*</url-pattern>
49 </filter-mapping>
50 <filter>
51 <filter-name>struts2</filter-name>
52 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
53 </filter>
54 <filter-mapping>
55 <filter-name>struts2</filter-name>
56 <url-pattern>/*</url-pattern>
57 </filter-mapping>
58 <filter>
59 <filter-name>openSessionInViewFilter</filter-name>
60 <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
61 <init-param>
62 <param-name>sessionFactoryBeanName</param-name>
63 <param-value>sessionFactory</param-value>
64 </init-param>
65 <init-param>
66 <param-name>singleSession</param-name>
67 <param-value>true</param-value>
68 </init-param>
69 <init-param>
70 <param-name>flushMode</param-name>
71 <param-value>AUTO</param-value>
72 </init-param>
73 </filter>
74 <filter-mapping>
75 <filter-name>openSessionInViewFilter</filter-name>
76 <url-pattern>/*</url-pattern>
77 </filter-mapping>
78
79 <welcome-file-list>
80 <welcome-file>index.jsp</welcome-file>
81 </welcome-file-list>
82 <error-page>
83 <error-code>404</error-code>
84 <location>/WEB-INF/errorPage/404.jsp</location>
85 </error-page>
86 <error-page>
87 <error-code>500</error-code>
88 <location>/WEB-INF/errorPage/500.jsp</location>
89 </error-page>
90 </web-app>


Spring配置文件(applicationContext-common.xml):

  1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
6 xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans.xsd
9 http://www.springframework.org/schema/tx
10 http://www.springframework.org/schema/tx/spring-tx.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop.xsd
13 http://www.springframework.org/schema/jee
14 http://www.springframework.org/schema/jee/spring-jee.xsd
15 http://www.springframework.org/schema/context
16 http://www.springframework.org/schema/context/spring-context.xsd
17 http://www.springframework.org/schema/util
18 http://www.springframework.org/schema/util/spring-util.xsd
19 http://www.springframework.org/schema/tool
20 http://www.springframework.org/schema/tool/spring-tool.xsd"
21 default-lazy-init="true" default-autowire="byName">
22
23 <bean id="propertyConfigurer"
24 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
25 <property name="locations">
26 <list>
27 <value>classpath:/dataBaseInfo.properties</value>
28 </list>
29 </property>
30 </bean>
31
32 <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"
33 p:jndiName="java:comp/env/jdbc/MySSH" /> -->
34
35 <!-- BoneCP -->
36 <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
37 p:driverClass="${jdbc.driver}" p:jdbcUrl="${jdbc.url}" p:username="${jdbc.username}"
38 p:password="${jdbc.password}" p:idleConnectionTestPeriodInMinutes="${idleConnectionTestPeriodInMinutes}"
39 p:idleMaxAgeInMinutes="${idleMaxAgeInMinutes}"
40 p:maxConnectionsPerPartition="${maxConnectionsPerPartition}"
41 p:minConnectionsPerPartition="${minConnectionsPerPartition}"
42 p:partitionCount="${partitionCount}" p:acquireIncrement="${acquireIncrement}"
43 p:statementsCacheSize="${statementsCacheSize}"
44 p:disableConnectionTracking="${disableConnectionTracking}"
45 p:releaseHelperThreads="${releaseHelperThreads}" destroy-method="close" />
46
47 <bean id="sessionFactory"
48 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
49 p:dataSource-ref="dataSource">
50
51 <property name="mappingDirectoryLocations">
52 <list>
53 <value>classpath:/com/eriloan/web/test/bo/</value>
54 </list>
55 </property>
56
57 <property name="hibernateProperties">
58 <props>
59 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
60 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
61 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
62 <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
63 <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
64 <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
65 <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
66 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
67 <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
68 <prop key="hibernate.order_updates">${hibernate.order_updates}</prop>
69 <prop key="hibernate.query.factory_class">${hibernate.query.factory_class}</prop>
70 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
71 <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
72 <!-- <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> -->
73 </props>
74 </property>
75 </bean>
76
77 <bean id="transactionManager"
78 class="org.springframework.orm.hibernate4.HibernateTransactionManager" />
79
80 <bean id="transactionInterceptor"
81 class="org.springframework.transaction.interceptor.TransactionInterceptor"
82 p:transactionManager-ref="transactionManager">
83 <property name="transactionAttributes">
84 <props>
85 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
86 <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
87 <prop key="select*">PROPAGATION_REQUIRED,readOnly</prop>
88 <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
89 <prop key="sync*">PROPAGATION_REQUIRED</prop>
90 <prop key="finish*">PROPAGATION_REQUIRED</prop>
91 <prop key="add*">PROPAGATION_REQUIRED</prop>
92 <prop key="insert*">PROPAGATION_REQUIRED</prop>
93 <prop key="edit*">PROPAGATION_REQUIRED</prop>
94 <prop key="update*">PROPAGATION_REQUIRED</prop>
95 <prop key="save*">PROPAGATION_REQUIRED</prop>
96 <prop key="remove*">PROPAGATION_REQUIRED</prop>
97 <prop key="delete*">PROPAGATION_REQUIRED</prop>
98 <prop key="*">PROPAGATION_REQUIRED,-java.lang.Exception</prop>
99 </props>
100 </property>
101 </bean>
102
103 <bean id="ProxyCreator"
104 class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
105 p:beanNames="*Service,*ServiceImpl" p:interceptorNames="transactionInterceptor" />
106
107 <!-- 数据库操作Bean -->
108 <bean id="dao" class="dao.DaoImpl" scope="singleton" />
109
110 <!--Service 原始Bean -->
111 <bean id="baseService" class="service.BaseServiceImpl" scope="singleton" />
112
113 <!--Action 原始Bean -->
114 <bean id="baseAction" class="action.BaseAction" scope="prototype" />
115
116 </beans>

SpringBean配置文件(applicationContext-beans.xml):

 1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
6 xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans.xsd
9 http://www.springframework.org/schema/tx
10 http://www.springframework.org/schema/tx/spring-tx.xsd
11 http://www.springframework.org/schema/aop
12 http://www.springframework.org/schema/aop/spring-aop.xsd
13 http://www.springframework.org/schema/jee
14 http://www.springframework.org/schema/jee/spring-jee.xsd
15 http://www.springframework.org/schema/context
16 http://www.springframework.org/schema/context/spring-context.xsd
17 http://www.springframework.org/schema/util
18 http://www.springframework.org/schema/util/spring-util.xsd
19 http://www.springframework.org/schema/tool
20 http://www.springframework.org/schema/tool/spring-tool.xsd"
21 default-lazy-init="true" default-autowire="byName" >
22
23 <!-- Test Bean By Eric Shi -->
24 <bean id="testService"
25 class="com.eriloan.web.test.service.impl.TestServiceImpl"
26 scope="singleton" />
27 <bean id="testAction" class="com.eriloan.web.test.action.TestAction"
28 scope="prototype" />
29
30
31 </beans>

Struts2 配置主配置文件(struts.xml):

 1 <?xml version="1.0" encoding="UTF-8" ?>
2
3 <!DOCTYPE struts PUBLIC
4 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
5 "http://struts.apache.org/dtds/struts-2.3.dtd">
6
7 <struts>
8 <include file="struts-default.xml" />
9
10 <!-- 默认的配置包 -->
11 <package name="defaultPackage" extends="struts-default,json-default,jfreechart-default,spring-default">
12
13
14 <global-results>
15 <!-- 公用返回页面 -->
16 <result name="error" type="dispatcher">/errorPage/index.jsp</result>
17 <result name="login" type="dispatcher">/login.jsp</result>
18 <result name="defaultLogin" type="redirect">/quitSys.jsp</result>
19 <result name="loginOut" type="redirect">/loginAction!loginPage.action
20 </result>
21 <result name="ajaxJson" type="json">
22 <param name="contentType">text/html</param>
23 <param name="root">ajax_json</param>
24 </result>
25 <!-- 异常返回页面 -->
26 <result name="actionException" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
27 </result>
28 <result name="serviceException" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
29 </result>
30 <result name="daoException" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
31 </result>
32 <result name="exception" type="dispatcher">/WEB-INF/errorPage/ServiceException.jsp
33 </result>
34 </global-results>
35 <!-- 异常处理 -->
36 <global-exception-mappings>
37 <!-- Action 层异常处理 -->
38 <exception-mapping result="actionException"
39 exception="system.exception.ActionException" />
40 <!-- Service 层异常处理 -->
41 <exception-mapping result="serviceException"
42 exception="system.exception.ServiceException" />
43 <!-- DAO 层异常处理 -->
44 <exception-mapping result="daoException"
45 exception="system.exception.DaoException" />
46 <!-- 未知的系统异常,后台没有对此信息进行归类 -->
47 <exception-mapping result="exception" exception="java.lang.Exception" />
48 </global-exception-mappings>
49 </package>
50
51 <!--前台调用静态方法-->
52 <!-- <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant> -->
53
54 <!-- Test by Eric -->
55 <include file="/struts-config/test/test_Struts.xml" />
56
57 </struts>

Struts 2业务配置文件(test_Struts.xml):

 1 <?xml version="1.0" encoding="UTF-8" ?>
2
3 <!DOCTYPE struts PUBLIC
4 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
5 "http://struts.apache.org/dtds/struts-2.3.dtd">
6
7 <struts>
8 <package name="testPackage" extends="defaultPackage">
9 <action name="testAction" class="testAction">
10 <!--Test Path-->
11 <result name="gotoTestPage" type="dispatcher">/page/test/testPage.jsp</result>
12 </action>
13 </package>
14 </struts>

Struts2 属性配置文件(struts.properties):

 1 struts.devMode=true
2 struts.action.extension=action
3 struts.objectFactory = spring
4 struts.objectFactory.spring.autoWire = name
5 struts.objectFactory.spring.useClassCache = true
6 struts.objectFactory.spring.autoWire.alwaysRespect = true
7 struts.configuration.xml.reload=true
8 struts.i18n.encoding = utf-8
9 struts.tag.altSyntax=true
10 struts.custom.i18n.resources=Eriloan_Text
11 struts.locale=zh_CN
12 struts.ui.theme = simple
13 struts.ognl.allowStaticMethodAccess=true
14 struts.multipart.maxSize=10000000000
15 #struts2.sslplugin.httpPort=8080
16 #struts2.sslplugin.httpsPort=8443
17 #struts2.sslplugin.annotations=true
18 #struts.multipart.parser=cos
19 #struts.multipart.parser=pell
20 struts.multipart.parser=jakarta
21 struts.multipart.saveDir=tempUpload

数据库配置文件:

 1 #MySQL配置
2 hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
3 #hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
4 #hibernate.dialect=org.hibernate.dialect.MySQLDialect
5 jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
6 jdbc.driver=com.mysql.jdbc.Driver
7 jdbc.username=root
8 jdbc.password=root
9
10 hibernate.show_sql=true
11 hibernate.format_sql=false
12 hibernate.use_sql_comments=false
13 hibernate.cache.use_second_level_cache=false
14 hibernate.cache.use_query_cache=false
15 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
16 hibernate.hbm2ddl.auto=update
17 hibernate.order_updates=true
18 hibernate.jdbc.batch_size=30
19 hibernate.jdbc.fetch_size=100
20 hibernate.max_fetch_depth=2
21
22 #hibernate4.0事务的模式
23 #1:org.hibernate.context.internal.ThreadLocalSessionContext - 通过线程来跟踪。
24 #2:org.hibernate.context.internal.JTASessionContext - 通过JTA来跟踪,和以前JTA的方法是一样的。
25 #3:org.hibernate.context.internal.ManagedSessionContext
26 #4:org.springframework.orm.hibernate4.SpringSessionContext - spring的事务管理。
27 hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
28 #Hibernate4.0的查询翻译器:
29 hibernate.query.factory_class=org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
30 #Hibernate3.0的查询翻译器:
31 #hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
32 #Hibernate2.1的查询翻译器
33 #hibernate.query.factory_class=org.hibernate.hql.classic.ClassicQueryTranslatorFactory
34
35
36 #Connection Pooling
37
38 #acquireIncrement: 当连接池中的连接耗尽的时候一次同时获取的连接数。Default: 3
39 #idleConnectionTestPeriod:检查数据库连接池中控线连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0
40 #idleMaxAge:连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0
41 #maxConnectionsPerPartition:每个分区最大的连接数
42 #minConnectionsPerPartition:每个分区最小的连接数
43 #partitionCount:分区数,默认值2,最小1,推荐3-4,视应用而定
44 #acquireIncrement:每次去拿数据库连接的时候一次性要拿几个,默认值:2
45 #statementsCacheSize:缓存prepared statements的大小,默认值:0
46 #releaseHelperThreads:每个分区释放链接助理进程的数量,默认值:3,除非你的一个数据库连接的时间内做了很多工作,不然过多的助理进程会影响你的性能
47
48 minPoolSize=5
49 maxPoolSize=20
50 maxIdleTime=1800
51 idleConnectionTestPeriodInMinutes=240
52 maxStatements=0
53 idleMaxAgeInMinutes=240
54 maxConnectionsPerPartition=30
55 minConnectionsPerPartition=5
56 partitionCount=3
57 acquireIncrement=5
58 statementsCacheSize=50
59 releaseHelperThreads=2
60 disableConnectionTracking=true

Dao代码:

  1 package dao;
2
3 import java.io.Serializable;
4 import java.util.Iterator;
5 import java.util.List;
6 import java.util.Map;
7
8 import org.apache.log4j.Logger;
9 import org.hibernate.Query;
10 import org.hibernate.SessionFactory;
11
12 import system.exception.DaoException;
13 import bo.PageEntity;
14 import dao.hqlProvider.IHqlProviderSet;
15
16 /**
17 *
18 * <p>Copyright: All Rights Reserved</p>
19 * <p>Company: 北京新线科技发展有限公司 http://www.NewLineTech.cn</p>
20 * <p>Description: Dao实现类 </p>
21 *
22 * @author:Eric
23 */
24 public class DaoImpl implements IDao{
25 protected Logger log = Logger.getLogger(DaoImpl.class);
26
27 /**
28 * Hibernate Session 工厂
29 */
30 private SessionFactory sessionFactory;
31
32 /**
33 *
34 * <br/>Description:根据传入的实体向数据库添加一条记录
35 *
36 * @author Eric
37 * @param obj
38 * @throws DaoException
39 */
40 public void addObject(Object obj) throws DaoException{
41 log.debug("BaseDao addObject object " + obj);
42 try{
43 sessionFactory.getCurrentSession().save(obj);
44 }catch(Exception e){
45 throw new DaoException("根据传入对象添加记录异常,请联系管理员!",e);
46 }
47 }
48
49 /**
50 *
51 * <br/>Description:强制刷新Hibernate缓存提交数据更改操作
52 *
53 * @author Eric
54 * @return
55 * @version V1.0
56 */
57 public void dbFlush() throws DaoException{
58 log.debug("BaseDao addObject dbFlush");
59 try{
60 sessionFactory.getCurrentSession().flush();
61 }catch(Exception e){
62 throw new DaoException("刷新缓存失败,请联系管理员!",e);
63 }
64 }
65
66 /**
67 *
68 * <br/>Description:根据传入的实体向数据库添加一条记录,返回插入记录的主键
69 *
70 * @author Eric
71 * @param obj
72 * @return
73 * @throws DaoException
74 */
75 public String addObjectPK(Object obj) throws DaoException{
76 log.debug("BaseDao addObjectPK object " + obj);
77 String id = null;
78 try{
79 id = (String) sessionFactory.getCurrentSession().save(obj);
80 }catch(Exception e){
81 throw new DaoException("根据传入对象添加记录异常,请联系管理员!",e);
82 }
83 return id;
84 }
85
86 /**
87 *
88 * <br/>Description:根据传入的实体从数据库删除一条记录
89 *
90 * @author Eric
91 * @param obj
92 * @throws DaoException
93 */
94 public void deleteObject(Object obj) throws DaoException{
95 log.debug("BaseDao deleteObject object " + obj);
96 try{
97 sessionFactory.getCurrentSession().delete(obj);
98 }catch(Exception e){
99 throw new DaoException("根据传入对象删除记录异常,请联系管理员!",e);
100 }
101 }
102
103 /**
104 *
105 * <br/>Description:根据传入的实体与ID从数据库删除一条记录
106 *
107 * @author Eric
108 * @param cls
109 * @param id
110 * @throws DaoException
111 */
112 @SuppressWarnings({"rawtypes"})
113 public void deleteObject(Class cls,Serializable id) throws DaoException{
114 log.debug("BaseDao deleteObject Class " + cls.getName() + " id " + id.toString());
115 try{
116 this.deleteObject(sessionFactory.getCurrentSession().get(cls,id));
117 }catch(Exception e){
118 throw new DaoException("根据传入对象与ID删除记录异常,请联系管理员!",e);
119 }
120 }
121
122 /**
123 *
124 * <br/>Description:根据传入的实体修改数据库中一条记录
125 *
126 * @author Eric
127 * @param obj
128 * @throws DaoException
129 */
130 public void updateObject(Object obj) throws DaoException{
131 log.debug("BaseDao updateObject object " + obj);
132 try{
133 sessionFactory.getCurrentSession().update(obj);
134 }catch(Exception e){
135 throw new DaoException("根据传入对象更新记录异常,请联系管理员!");
136 }
137 }
138
139 /**
140 *
141 * <br/>Description:根据传入的实体修改数据库中一条记录,返回更新记录的主键
142 *
143 * @author Eric
144 * @param obj
145 * @return
146 * @throws DaoException
147 */
148 public String updateObjectPK(Object obj) throws DaoException{
149 log.debug("BaseDao updateObjectPK object " + obj);
150 String id = null;
151 try{
152 id = this.addObjectPK(obj);
153 }catch(Exception e){
154 throw new DaoException("根据传入对象更新记录异常,请联系管理员!",e);
155 }
156 return id;
157 }
158
159 /**
160 *
161 * <br/>Description:根据传入的实体添加或修改数据库中一条记录
162 *
163 * @author Eric
164 * @param obj
165 * @throws DaoException
166 */
167 public void addOrUpdate(Object obj) throws DaoException{
168 log.debug("BaseDao updateObjectPK object " + obj);
169 try{
170 sessionFactory.getCurrentSession().saveOrUpdate(obj);
171 }catch(Exception e){
172 throw new DaoException("根据传入对象保存数据异常,请联系管理员!",e);
173 }
174 }
175
176 /**
177 *
178 * <br/>Description:根据ID返回一个对象
179 *
180 * @author Eric
181 * @param cls
182 * @param id
183 * @return
184 * @throws DaoException
185 */
186 @SuppressWarnings({"rawtypes"})
187 public Object findObjectById(Class cls,Serializable id) throws DaoException{
188 log.debug("BaseDao findObjectById Class " + cls.getName() + " id " + id.toString());
189 Object obj = null;
190 try{
191 obj = sessionFactory.getCurrentSession().get(cls,id);
192 }catch(Exception e){
193 throw new DaoException("根据对象及ID查询记录异常,请联系管理员!",e);
194 }
195 return obj;
196 }
197
198 /**
199 *
200 * <br/>Description:根据实体返回一个集合
201 *
202 * @author Eric
203 * @param cls
204 * @return
205 * @throws DaoException
206 */
207 @SuppressWarnings({"rawtypes"})
208 public List findAllData(Class cls) throws DaoException{
209 log.debug("BaseDao findAllData Class " + cls.getName());
210 List list = null;
211 try{
212 list = sessionFactory.getCurrentSession().createQuery(" from " + cls.getName() + "").list();
213 }catch(Exception e){
214 throw new DaoException("根据对象查询记录异常,请联系管理员!",e);
215 }
216 return list;
217 }
218
219 /**
220 *
221 * <br/>Description:根据传入HQL语句返回一个集合(供DAO使用)
222 *
223 * @author Eric
224 * @param hql
225 * @return
226 * @throws DaoException
227 */
228 @SuppressWarnings("rawtypes")
229 public List findHQLObject(String hql) throws DaoException{
230 try{
231 return sessionFactory.getCurrentSession().createQuery(hql).list();
232 }catch(Exception e){
233 throw new DaoException("根据传入条件语句查询记录异常,请联系管理员!");
234 }
235 }
236
237 /**
238 *
239 * <br/>Description:按HQL提供者别名与条件查询集合
240 *
241 * @author Eric
242 * @param hqlProviderSet
243 * @param queryName
244 * @param paramMap
245 * @return
246 * @throws DaoException
247 */
248 @SuppressWarnings("rawtypes")
249 public List findListByHqlName(IHqlProviderSet hqlProviderSet,String queryName,Map paramMap) throws DaoException{
250 String hql;
251 try{
252 hql = hqlProviderSet.getHqlByQryName(queryName);
253 Query query = sessionFactory.getCurrentSession().createQuery(hql);
254 if(paramMap != null){
255 hqlArgs(paramMap,query);
256 }
257
258 return query.list();
259 }catch(Exception e){
260 throw new DaoException("按HQL提供者别名与条件查询集合异常,请联系管理员!",e);
261 }
262 }
263
264 /**
265 *
266 * <br/>Description:按HQL提供者别名、条件、分页信息查询集合
267 *
268 * @author Eric
269 * @param hqlProviderSet
270 * @param queryName
271 * @param paramMap
272 * @param page
273 * @return
274 * @throws DaoException
275 */
276 @SuppressWarnings("rawtypes")
277 public List findListByHqlName(IHqlProviderSet hqlProviderSet,String queryName,Map paramMap,PageEntity page) throws DaoException{
278 String hql;
279 try{
280 hql = hqlProviderSet.getHqlByQryName(queryName);
281
282 Query query = sessionFactory.getCurrentSession().createQuery(hql);
283
284 if(paramMap != null){
285 hqlArgs(paramMap,query);
286 }
287
288 query.setFirstResult((page.getPageNo() - 1) * page.getPageSize());
289 query.setMaxResults(page.getPageSize());
290
291 return query.list();
292 }catch(Exception e){
293 throw new DaoException("按HQL提供者别名、条件、分页信息查询集合异常,请联系管理员!",e);
294 }
295 }
296
297 /**
298 *
299 * <br/>Description:根据传入实体对象返回总记录数
300 *
301 * @author Eric
302 * @param cls
303 * @return
304 * @throws DaoException
305 */
306 @SuppressWarnings("rawtypes")
307 public int findIntRowCountByHqlName(Class cls) throws DaoException{
308 try{
309 Query query = sessionFactory.getCurrentSession().createQuery(" select count(c.id) from " + cls.getName() + " c ");
310 List list = query.list();
311 int rowCount = ((Number) list.get(0)).intValue();
312 return rowCount;
313 }catch(Exception e){
314 throw new DaoException("查询记录总数异常,请联系管理员!",e);
315 }
316 }
317
318 /**
319 *
320 * <br/>Description:根据HQL提供者别名与条件查询记录总数
321 *
322 * @author Eric
323 * @param hqlProviderSet
324 * @param queryName
325 * @param paramMap
326 * @return
327 * @throws DaoException
328 */
329 @SuppressWarnings("rawtypes")
330 public int findIntRowCountByHqlName(IHqlProviderSet hqlProviderSet,String queryName,Map paramMap) throws DaoException{
331 String hql;
332 try{
333 hql = hqlProviderSet.getHqlByQryName(queryName);
334 Query query = sessionFactory.getCurrentSession().createQuery(hql);
335 if(paramMap != null){
336 hqlArgs(paramMap,query);
337 }
338 List list = query.list();
339 int rowCount = ((Number) list.get(0)).intValue();
340 return rowCount;
341 }catch(Exception e){
342 throw new DaoException("执行带参数的查询记录总数异常,请联系管理员!",e);
343 }
344 }
345
346 /**
347 *
348 * <br/>Description:为Hibernate查询设置参数
349 *
350 * @author Eric
351 * @param argsMap
352 * @param query
353 */
354 @SuppressWarnings("rawtypes")
355 public void hqlArgs(Map argsMap,Query query){
356 Iterator itKey = argsMap.keySet().iterator();
357 while(itKey.hasNext()){
358 String key = (String) itKey.next();
359 @SuppressWarnings("unused")
360 Object obj = argsMap.get(key);
361 if(argsMap.get(key) instanceof List){
362 query.setParameterList(key,(List) argsMap.get(key));
363 }else{
364 query.setParameter(key,argsMap.get(key));
365 }
366 }
367 }
368
369 public SessionFactory getSessionFactory(){
370 return sessionFactory;
371 }
372
373 public void setSessionFactory(SessionFactory sessionFactory){
374 this.sessionFactory = sessionFactory;
375 }
376 }

Jar包:


posted on 2012-02-29 21:47  日虾夜饺  阅读(2424)  评论(0编辑  收藏  举报

导航