SpringMVC配置

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>gamble</groupId>
	<artifactId>gamble</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
 
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.1</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>

		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>1.9</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.1</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.webflow</groupId>
			<artifactId>spring-webflow</artifactId>
			<version>2.3.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.webflow</groupId>
			<artifactId>spring-faces</artifactId>
			<version>2.3.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.10.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>3.6.10.Final</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-lgpl</artifactId>
			<version>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-lgpl</artifactId>
			<version>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-xc</artifactId>
			<version>1.3.0</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.25</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>proxool</groupId>
			<artifactId>proxool</artifactId>
			<version>0.9.1</version>
		</dependency>
		
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.0</version>
		</dependency>

		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>

		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernatespatial</groupId>
			<artifactId>hibernate-spatial-mysql</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernatespatial</groupId>
			<artifactId>hibernate-spatial</artifactId>
			<version>1.1</version>
		</dependency>

		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>2.0.2</version>
		</dependency>

		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>springsource-repo</id>
			<name>SpringSource Repository</name>
			<url>http://repo.springsource.org/release</url>
		</repository>
		<repository>
			<id>springsource-repository</id>
			<name>Spring Maven Releases, Milestones, and Snapshots</name>
			<url>http://repo.springsource.org/snapshot</url>
		</repository>
		<repository>
			<id>hibernate-orm</id>
			<name>Hibernate ORM</name>
			<url>http://repo1.maven.org/maven2/org/hibernate/hibernate-core</url>
		</repository>
		<repository>
			<id>terracotta-releases</id>
			<url>http://www.terracotta.org/download/reflector/releases</url>
		</repository>
		<repository>
			<id>cloudhopper-releases</id>
			<url>http://maven.cloudhopper.com/repos/third-party</url>
		</repository>
		<repository>
			<id>OSGEO GeoTools repo</id>
			<url>http://download.osgeo.org/webdav/geotools</url>
		</repository>
		<repository>
			<id>Hibernate Spatial repo</id>
			<url>http://www.hibernatespatial.org/repository</url>
		</repository>
	</repositories>
</project>

spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 	   xmlns:aop="http://www.springframework.org/schema/aop" 
 	   xmlns:context="http://www.springframework.org/schema/context"
 	   xmlns:p="http://www.springframework.org/schema/p" 
 	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   						   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
   						   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   						   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.sy" />
 	
 	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:resources.properties</value>
            </list>
        </property>
    </bean>
    
   	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >
    	<property name="dataSource" ref="dataSource"/>
    	<property name="packagesToScan">
			<list>
				<value>com.sy.gamble.entity</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">true</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
            </props>
        </property>
  	</bean>

  	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${connection.driver_class}" />
		<property name="jdbcUrl" value="${connection.url}" />
		<property name="user" value="${connection.username}" />
		<property name="password" value="${connection.password}" />
		<property name="minPoolSize" value="${proxool.maximum.connection.count}"/>
		<property name="maxPoolSize" value="${proxool.minimum.connection.count}" />
		<property name="initialPoolSize" value="${proxool.init.connection.count}" /> 
		<property name="autoCommitOnClose" value="false" /> 
	</bean>
	
	<!-- 开启注解事务 只对当前配置文件有效 -->
  	<tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!--事物管理 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="newTran*" propagation="REQUIRES_NEW" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<aop:config>
		<aop:pointcut id="syService"
			expression="execution(public* com.*.*.service.*.*(..))" />
		<aop:advisor pointcut-ref="syService" advice-ref="txAdvice" />
	</aop:config>

</beans>

spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/util
        				http://www.springframework.org/schema/util/spring-util-3.1.xsd
        				http://www.springframework.org/schema/beans 
        				http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        				http://www.springframework.org/schema/context 
        				http://www.springframework.org/schema/context/spring-context-3.1.xsd
        				http://www.springframework.org/schema/mvc
       					http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd" >
    
    <!-- 会自动注册了validator  ConversionService  -->
    <mvc:annotation-driven />
    <context:component-scan base-package="com.sy">
    	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
    
    <!-- ========================= VIEW定义 ========================= -->
    <!-- bean name view resolver-->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0"/>  
    
    <!-- 根据客户端的不同的请求决定不同的 view进行响应, 如 /blog/1.json /blog/1.xml -->  
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="1">  
        <!-- 设置为true以忽略对Accept Header的支持-->  
        <!-- 扩展名至mimeType的映射,即 /user.json => application/json -->  
        <property name="favorPathExtension" value="false"/>  
        
         <!-- 用于开启 /userinfo/123?format=json 的支持 -->  
         <property name="favorParameter" value="false"/>  
         
        <property name="mediaTypes">  <!--favorPathExtension, favorParameter是true时才起作用  -->
            <map>  
                <entry key="html" value="*"/>
            </map>  
         </property>  
         <property name="viewResolvers">  
             <list>  
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                    <property name="contentType" value="text/html"/>
                    <property name="prefix" value="/WEB-INF/jsp/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>  
        </property>  
    </bean>  
 

    <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="3">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html"/>        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- json view -->
    <bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
    
    <!-- 文件上传相关 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--one of the properties available;the maximum file size in bytes-->
        <property name="maxUploadSize" value="100000"/>
    </bean>
     
</beans>

resource.properties

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
hibernate.hbm2ddl.auto=none
hibernate.show_sql=false
hibernate.query.substitutions=true 1, false 0
hibernate.default_batch_fetch_size=16
hibernate.max_fetch_depth=2
hibernate.bytecode.use_reflection_optimizer=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.EhCacheRegionFactory
net.sf.ehcache.configurationResourceName=/ehcache_hibernate.xml
hibernate.cache.use_structured_entries=true
hibernate.generate_statistics=true


connection.driver_class=com.mysql.jdbc.Driver
connection.url=jdbc:mysql://182.92.222.57:3306/ad?useUnicode=true&characterEncoding=utf8
connection.username=root
connection.password=6BB4837EB74329
#connection.url=jdbc:mysql://localhost:3306/wx_game?useUnicode=true&characterEncoding=utf8
#connection.username=root
#connection.password=nxN2HyqCWqXq

proxool.maximum.connection.count=5
proxool.minimum.connection.count=2
proxool.init.connection.count=1

log4j.properties

 ### set log levels ###
 log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 
log4j.logger.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE
log4j.logger.org.hibernate.engine.QueryParameters=DEBUG 
log4j.logger.org.hibernate.engine.query.HQLQueryPlan=DEBUG 

log4j.rootLogger =info,CONSOLE,D,E

### write info to system.out ###
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 
log4j.appender.CONSOLE.Target=System.out 
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 
log4j.appender.CONSOLE.Threshold = DEBUG 
log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %5p[%t](%F:%L)- %m%n
#log4j.appender.CONSOLE.layout.ConversionPattern=[%-4L] %d - %c -%-4r [%t] %-5p  %x - %m%n 

### log debug info into debug.log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/dubugOpenMethod.log 
log4j.appender.D.Append = true
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### log error info into error.log file ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = logs/errorOpenMethod.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

BaseDao.java

package com.sy.gamble.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@SuppressWarnings("unchecked")
@Repository("baseDao")
public class BaseDao
{
	private static final Logger logger = LoggerFactory.getLogger(BaseDao.class);

	@Resource(name = "hibernateTemplate")
	HibernateTemplate hibernateTemplate;

	public <T> boolean addEntity(T t)
	{
		boolean flag = false;
		try
		{
			// 将Entity添加到数据中
			this.hibernateTemplate.persist(t);
			flag = true;
			logger.info("Add Entity[" + t + "] success.");
		} catch (RuntimeException e)
		{
			logger.error("Add Entity[" + t + "] fail. Message:" + e.getMessage(), e);
			throw e;
		}
		return flag;
	}

	public <T> Serializable saveEntity(T t)
	{
		Serializable pk = null;
		try
		{
			pk = this.hibernateTemplate.save(t);
			logger.info("Add Entity[" + t + "] success.");
		} catch (RuntimeException e)
		{
			logger.error("Add Entity[" + t + "] fail. Message:" + e.getMessage(), e);
			throw e;
		}
		return pk;
	}

	public <T> boolean updateEntity(T t)
	{
		boolean flag = false;
		try
		{
			this.hibernateTemplate.update(t);
			flag = true;
			logger.info("Update Entity[" + t + "] success.");
		} catch (RuntimeException e)
		{
			logger.error("Update Entity[" + t + "] fail. Message:" + e.getMessage(), e);
			throw e;
		}
		return flag;
	}

	public <T> boolean deleteEntity(T t)
	{
		boolean flag = false;
		try
		{
			this.hibernateTemplate.delete(t);
			flag = true;
			logger.info("Delete Entity[" + t + "] success.");
		} catch (RuntimeException e)
		{
			logger.error("Delete Entity[" + t + "] fail. Message:" + e.getMessage(), e);
			throw e;
		}
		return flag;
	}

	public <T> T findEntityByPK(Class<T> cla, Serializable pk)
	{
		T t = null;
		try
		{
			t = this.hibernateTemplate.get(cla, pk);
			logger.info("find Entity[" + t + "] success.");
		} catch (RuntimeException e)
		{
			logger.error("find Entity[" + t + "] fail. Message:" + e.getMessage(), e);
			throw e;
		}
		return t;
	}

	public <T> List<T> findAllEntity(Class<T> cla)
	{
		List<T> list = null;
		list = this.hibernateTemplate.find("from " + cla.getName());
		return list;
	}

	public <T> List<T> findEntityByHql(String hql, Object... params)
	{
		List<T> list = null;
		list = this.hibernateTemplate.find(hql, params);
		return list;
	}

	public boolean executeUpdateSQL(final String sql, final Map<String, Object> params)
	{
		boolean flag = false;
		int row = this.hibernateTemplate.execute(new HibernateCallback<Integer>()
		{
			public Integer doInHibernate(Session session) throws HibernateException
			{
				SQLQuery query = session.createSQLQuery(sql);
				if (params != null)
				{
					for (String key : params.keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				int row = query.executeUpdate();
				return row;
			}
		});
		if (row > 0)
			flag = true;
		return flag;
	}

	public <T> List<T> executeListSQL(final String sql, final Map<String, Object> params)
	{
		return this.hibernateTemplate.execute(new HibernateCallback<List<T>>()
		{
			public List<T> doInHibernate(Session session) throws HibernateException
			{
				SQLQuery query = session.createSQLQuery(sql);
				if (params != null && params.size() > 0)
				{
					for (String key : params.keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				return query.list();
			}
		});
	}

	public boolean executeUpdateHQL(final String hql, @SuppressWarnings("rawtypes") final Map params)
	{
		boolean flag = false;
		int row = this.hibernateTemplate.execute(new HibernateCallback<Integer>()
		{
			public Integer doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery(hql);
				if (params != null)
				{
					for (String key : ((Map<String, Object>) params).keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				int row = query.executeUpdate();
				return row;
			}
		});

		if (row > 0)
			flag = true;
		return flag;
	}

	public <T> List<T> executeListHQL(final String hql, final Map<String, Object> params)
	{
		return this.hibernateTemplate.execute(new HibernateCallback<List<T>>()
		{
			public List<T> doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery(hql);
				if (params != null && params.size() > 0)
				{
					for (String key : ((Map<String, Object>) params).keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				return query.list();
			}
		});
	}

	public <T> T executeUniqueHQL(final String hql, final Map<String, Object> params)
	{
		return (T) this.hibernateTemplate.execute(new HibernateCallback<Object>()
		{
			public Object doInHibernate(Session session) throws HibernateException, SQLException
			{
				Query query = session.createQuery(hql);
				if (params != null && params.size() > 0)
				{
					for (String key : ((Map<String, Object>) params).keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				query.setMaxResults(1);
				return query.uniqueResult();
			}

		});
	}

	public <T> T executeHQLLimit(final String hql, final Map<String, Object> params, final int firstNum, final int maxNum)
	{
		return (T) this.hibernateTemplate.execute(new HibernateCallback<Object>()
		{
			public Object doInHibernate(Session session) throws HibernateException, SQLException
			{
				Query query = session.createQuery(hql);
				if (params != null && params.size() > 0)
				{
					for (String key : ((Map<String, Object>) params).keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				query.setFirstResult(firstNum);
				query.setMaxResults(maxNum);
				return query.list();
			}

		});
	}

	public <T> T executeUniqueHQL(final Class<T> cla)
	{
		return (T) this.hibernateTemplate.execute(new HibernateCallback<Object>()
		{
			public Object doInHibernate(Session session) throws HibernateException, SQLException
			{
				String hql = "from " + cla.getName();
				Query query = session.createQuery(hql);
				query.setMaxResults(1);
				return query.uniqueResult();
			}
		});
	}

	public <T> List<T> getListForPage(final Class<T> arg, final Criterion[] criterions, final int offset, final int length)
	{
		return this.hibernateTemplate.executeFind(new HibernateCallback<List<T>>()
		{
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException
			{
				Criteria criteria = session.createCriteria(arg);
				// 循环遍历添加约束条件
				for (int i = 0; i < criterions.length; i++)
				{
					if (criterions[i] != null)
					{
						criteria.add(criterions[i]);
					}
				}
				criteria.setFirstResult(offset);
				criteria.setMaxResults(length);
				return criteria.list();
			}
		});

	}

	public <T> List<T> findByCriteria(final DetachedCriteria detachedCriteria)
	{
		return this.hibernateTemplate.executeFind(new HibernateCallback<List<T>>()
		{
			@Override
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException
			{
				Criteria criteria = detachedCriteria.getExecutableCriteria(session);
				return criteria.list();
			}
		});
	}

	public <T> List<T> findByCriteria(final DetachedCriteria detachedCriteria, final int first, final int max)
	{
		return this.hibernateTemplate.executeFind(new HibernateCallback<List<T>>()
		{
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException
			{
				Criteria criteria = detachedCriteria.getExecutableCriteria(session);
				criteria.setFirstResult(first).setMaxResults(max);
				return criteria.list();
			}
		});
	}

	public <T> T executeCountListHQL(final String hql, final Map<String, Object> params)
	{
		return (T) this.hibernateTemplate.execute(new HibernateCallback<Object>()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery(hql);
				if (params != null && params.size() > 0)
				{
					for (String key : params.keySet())
					{
						query.setParameter(key, params.get(key));
					}
				}
				return query.uniqueResult();
			}
		});
	}

	public <T> T executeCountByCriterion(final Class<T> arg, final Criterion[] criterions)
	{
		return (T) this.hibernateTemplate.execute(new HibernateCallback<Object>()
		{
			public Object doInHibernate(Session session) throws HibernateException, SQLException
			{
				Criteria criteria = session.createCriteria(arg);
				// 循环遍历添加约束条件
				for (int i = 0; i < criterions.length; i++)
				{
					if (criterions[i] != null)
					{
						criteria.add(criterions[i]);
					}
				}
				criteria.setProjection(Projections.rowCount());
				return criteria.uniqueResult();
			}
		});
	}

	public <T> List<T> executeByCriterion(final Class<T> cla, final Criterion[] criterions)
	{
		return this.hibernateTemplate.execute(new HibernateCallback<List<T>>()
		{
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException
			{
				Criteria criteria = session.createCriteria(cla);
				// 循环遍历添加约束条件
				for (int i = 0; i < criterions.length; i++)
				{
					if (criterions[i] != null)
					{
						criteria.add(criterions[i]);
					}
				}
				return criteria.list();
			}
		});

	}

	public <T> List<T> executeByCriterionAndOrder(final Class<T> cla, final Criterion[] criterions, final Order[] orders)
	{
		return this.hibernateTemplate.execute(new HibernateCallback<List<T>>()
		{
			public List<T> doInHibernate(Session session) throws HibernateException, SQLException
			{
				Criteria criteria = session.createCriteria(cla);
				// 循环遍历添加约束条件
				for (int i = 0; i < criterions.length; i++)
				{
					if (null != criterions[i])
					{
						criteria.add(criterions[i]);
					}
				}
				// 循环遍历体添加查询条件
				for (int k = 0; k < orders.length; k++)
				{
					if (null != orders[k])
					{
						criteria.addOrder(orders[k]);
					}
				}
				return criteria.list();
			}
		});
	}

}

BaseService.java

package com.sy.gamble.service;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sy.gamble.dao.BaseDao;

@Service
public class BaseService
{
	private static final Logger logger = LoggerFactory.getLogger(BaseService.class);

	@Resource(name = "baseDao")
	BaseDao baseDao;

	public <T> boolean addEntity(T t)
	{
		boolean flag = false;
		try
		{
			flag = baseDao.addEntity(t);
		} catch (Exception e)
		{
			logger.error("In BaseService , add entity have a error." + e.getMessage());
		}
		return flag;
	}

	public <T> boolean updateEntity(T t)
	{
		boolean flag = false;
		try
		{
			flag = baseDao.updateEntity(t);
		} catch (Exception e)
		{
			logger.error("In BaseService, update Entity have a error." + e.getMessage());
		}
		return flag;
	}

	public <T> boolean deleteEntity(T t)
	{
		boolean flag = false;
		try
		{
			flag = baseDao.deleteEntity(t);
		} catch (Exception e)
		{
			logger.error("In BaseService, update Entity have a error." + e.getMessage());
		}
		return flag;
	}

	public <T> boolean deleteEntityByPk(Class<T> cla, Serializable pk)
	{
		boolean flag = false;
		try
		{
			T t = baseDao.findEntityByPK(cla, pk);
			if (t != null)
				flag = baseDao.deleteEntity(t);
			else
				logger.info("Entity that you was choosed is not exists.");
		} catch (Exception e)
		{
			logger.error("In BaseService, delete Entity have a error." + e.getMessage());
		}
		return flag;
	}

	public <T> T findEntityByPK(Class<T> cla, Serializable pk)
	{
		T t = null;
		try
		{
			t = baseDao.findEntityByPK(cla, pk);
		} catch (Exception e)
		{
			logger.error("In BaseService, find Entity By PK have a error." + e.getMessage());
		}
		return t;
	}

	public <T> List<T> findEntityByAll(Class<T> cla)
	{
		List<T> entityList = null;
		entityList = baseDao.findAllEntity(cla);
		return entityList;
	}

}


你可能感兴趣的:(springMVC)