搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台

一. 开发环境

  1. 点击此查看并下载需要的 Eclipse IDE for Java EE Developers 开发工具,依赖于java,推荐选用32位

    2. 点击此查看并下载需要的 MySQL Server 数据库,推荐选用32位

  3. 点击此找到并下载  Java SE Development Kit 6u45,有些dll只能在32位上运行,推荐选用32位

  4. 点击此找到并下载  apache-tomcat-6.0.48.zip,兼容32位和64位版本

  5. 点击此下载 ims 工程文件

  6. 点击此查看 maven 私服搭建指南

  7. 点击此查看 maven 上传第三方jar

 

二. 工程搭建

  1. Eclipse --> File --> New --> Dynamic Web Project --> 输入工程名 ims --> Next -->

    修改 Default output folder 为:WebContent/WEB-INF/classes --> Finish

  2. 将下载的工程文件按目录复制到 ims 工程中

  注:ims全称:information management system

 

三. 工程目录结构介绍

  注:以下的xxx均表示子项目名称,如:

    子项目 sys 全称:system,基础信息、权限管理系统

    子项目 mms 全称:material management system,材料管理系统

    子项目 iot 全称:Internet of things,物联网系统

 

src
 |--com
 |   |--ims
 |   |   |--common
 |   |   |--persistence
 |   |   |       |--base
 |   |   |       |--dao
 |   |   |       |   |--xxx
 |   |   |       |       |--impl
 |   |   |       |--model
 |   |   |            |--xxx
 |   |   |--service
 |   |   |     |--xxx
 |   |   |         |--impl
 |   |   |--web
 |   |   |   |--controller
 |   |   |   |      |---xxx


WebContent
    |--common
    |--content
    |     |--css
    |     |--images
    |     |--js
    |--sql
    |   |--xxx
    |--view
    |   |--xxx
    |--viewModel
    |      |--xxx
View Code

  

四. jar包介绍

  1. spring-framework-4.3.4.RELEASE,可点击此下载并在 libs 文件夹下得到: 

spring-aop-4.3.4.RELEASE.jar
spring-beans-4.3.4.RELEASE.jar
spring-context-4.3.4.RELEASE.jar
spring-core-4.3.4.RELEASE.jar
spring-expression-4.3.4.RELEASE.jar
spring-jdbc-4.3.4.RELEASE.jar
spring-orm-4.3.4.RELEASE.jar
spring-tx-4.3.4.RELEASE.jar
spring-web-4.3.4.RELEASE.jar
spring-webmvc-4.3.4.RELEASE.jar
View Code

  2. aspectjweaver-1.8.9.jar,spring AOP 依赖 aspectj 来实现的,可点击此下载 

  3. jackson-2.3.0,springMVC利用@ResponBody标签将Map,List转为json返回,支持 spring-4.3.4 的最低版本,可点击此下载

jackson-annotations-2.3.0.jar
jackson-core-2.3.0.jar
jackson-databind-2.3.0.jar
View Code

 

  4. slf4j-1.7.21,spring 的日记记录采用:jc-over-slf4j ---> slf4j ---> log4j,可点击此下载得到:

jcl-over-slf4j-1.7.21.jar
slf4j-api-1.7.21.jar
slf4j-log4j12-1.7.21.jar
View Code

  5. log4j-1.2.17.jar,支持 java 1.6、spring-4.3.4 的最高稳定版本,可点击此下载  

  6. log4jdbc4-1.2.1.jar,jdbc层日志框架,可点击此下载

 

  7. hibernate-release-4.2.21.Final,支持 java 1.6 的最高版本,可点击此下载并在 libs/required 文件夹下得到:

antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.21.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
View Code

  8. mysql-connector-java-5.1.40-bin.jar,mysql驱动包,可点击此下载

 

  9. fastjson-1.2.21.jar

  10. commons-lang3-3.5.jar

  11. pom.xml

<properties>
  <org.slf4j-version>1.7.21</org.slf4j-version>
  <org.springframework.version>4.3.4.RELEASE</org.springframework.version>
  <com.fasterxml.jackson.core-version>2.3.0</com.fasterxml.jackson.coree-version>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework.version}</version>
  </dependency>
  <!-- spring AOP 依赖 aspectj 来实现 -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.9</version>
  </dependency>

  <!-- springMVC利用@ResponBody标签将Map,ListZ转为json返回 -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${com.fasterxml.jackson.core-version}</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${com.fasterxml.jackson.core-version}</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${com.fasterxml.jackson.core-version}</version>
  </dependency>
  
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
  </dependency>

  <!-- fastjson -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.21</version>
  </dependency>

  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${org.slf4j-version}</version>
  </dependency>

  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
  </dependency>

</dependencies>

<build>
  <finalName>ims</finalName>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-resources-plugin</artifactId>
      <version>2.7</version>
      <configuration>
        <encoding>UTF-8</encoding>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.5.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <encoding>UTF-8</encoding>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-clean-plugin</artifactId>
      <version>2.6.1</version>
      <configuration>
        <failOnError>false</failOnError>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-install-plugin</artifactId>
      <version>2.5.2</version>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>2.6</version>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-source-plugin</artifactId>
      <version>2.4</version>
      <executions>
        <execution>
          <id>attach-sources</id>
          <goals>
            <goal>jar</goal>
          </goals>
        </excution>
      </excutions>
    </plugin>
    <!-- 拷贝依赖包 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <version>2.10</version>
      <executions>
        <execution>
          <id>copy-dependencies</id>
          <phase>package</phase>
          <goals>
            <goal>copy-dependencies</goal>
          </goals>
          <configuration>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
            <excludeTransitive>false</excludeTransitive>
            <stripVersion>true</stripVersion>
          </configuration>
        </excution>
      </excutions>
    </plugin>
    <!-- 将打包后生成的jar复制到指定路径 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-antrun-plugin</artifactId>
      <executions>
        <execution>
          <id>copy-source</id>
          <phase>package</phase>
          <goals>
            <goal>run</goal>
          </goals>
          <configuration>
            <tasks>
              <copy tofile="${project.build.directory}/lib/${project.name}.${project.packaging}"
                    file="${project.build.directory}/${project.build.finalName}.${project.packaging}" />
            </tasks>
          </configuration>
        </excution>
      </excutions>
    </plugin>
  </plugins>

</build>
View Code


五. 配置文件介绍

  1. applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">  
    <context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="aspectj" expression="com.ims.persistence.dao..*.impl.*DaoImpl"/>
        <context:include-filter type="aspectj" expression="com.ims.service..*.impl.*BSImpl"/>
    </context:component-scan>   
    
    <!-- log4jdbc,需要依赖slf4j框架,拦截输出完整sql语句 -->
    <bean id="log4jdbcInterceptor" class="net.sf.log4jdbc.DataSourceSpyInterceptor" />
    <bean id="dataSourceLog4jdbcAutoProxyCreator"
        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="interceptorNames">
            <list>
                <value>log4jdbcInterceptor</value>
            </list>
        </property>
        <property name="beanNames">
            <list>                
                <value>xxxDatasource</value>
            </list>
        </property>
    </bean>
</beans>
View Code

  2. applicationContextXxx.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    
    <bean id="xxxDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />        
        <property name="url" value="jdbc:mysql://localhost:3306/xxx?characterEncoding=utf8" />        
        <property name="username" value="root" />        
        <property name="password" value="123456" />    
    </bean>
    
    <bean id="xxxSessionFactory" 
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">    
          <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <property name="dataSource" ref="xxxDatasource" />                                                    
        <property name="packagesToScan">
            <list>
                <value>com.ims.persistence.model.xxx</value>
            </list>    
        </property>        
    </bean>
    
    <bean id="xxxTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean>
    
    <tx:advice id="xxxTxAdvice" transaction-manager="xxxTransactionManager">   
        <tx:attributes>   
            <tx:method name="find*" isolation="READ_COMMITTED" read-only="true"/>
            <tx:method name="get*" isolation="READ_COMMITTED" read-only="true"/>
            <tx:method name="*" isolation="READ_COMMITTED" rollback-for="Throwable" />
        </tx:attributes>   
    </tx:advice>
    
    <aop:config>   
        <aop:pointcut id="xxxTxPointcut" expression="execution(* com.ims.service.xxx.impl..*BSImpl.*(..))"/>   
        <aop:advisor advice-ref="xxxTxAdvice" pointcut-ref="xxxTxPointcut" order="0"/>   
    </aop:config>   
    
    <bean id="xxxBaseDao" class="com.ims.persistence.dao.xxx.impl.XxxBaseDaoImpl">
        <property name="sessionFactory" ref="xxxSessionFactory"/>
    </bean> 
    
</beans>
View Code

  3. controllerServlet.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <mvc:annotation-driven />
    <context:component-scan base-package="com" use-default-filters="false">
        <context:include-filter type="aspectj" expression="com.ims.web.controller..*Controller"/>
    </context:component-scan>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/view/" />
    </bean>
</beans>
View Code

  4. hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>        
        <property name="hibernate.order_updates">true</property>        
        <property name="hibernate.show_sql">false</property>
        <!-- none -->
        <property name="hibernate.hbm2ddl.auto">update</property>        
        
        <property name="hibernate.c3p0.max_size">30</property>   
         <property name="hibernate.c3p0.min_size">5</property>    
         <property name="hibernate.c3p0.timeout">3000</property>
         <property name="hibernate.c3p0.max_statements">50</property>         
        <!--每隔多少秒检测连接是否可正常使用  -->    
        <property name="c3p0.idle_test_period">121</property>  
        <!--当池中的连接耗尽的时候,一次性增加的连接数量,默认为3-->    
        <property name="c3p0.acquire_increment">1</property>  
        <property name="c3p0.validate">true</property>
        
        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    </session-factory>
    
</hibernate-configuration>
View Code

  5. log4j.properties

#输出级别和输出位置 ; 包中只有级别大于或等于配置级别,才允许输出
log4j.rootLogger=WARN,console,roll

#控制台输出
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n

#按日期滚动输出
log4j.appender.roll=org.apache.log4j.DailyRollingFileAppender
log4j.appender.roll.File=${catalina.base}/logs/ims/ims.log
log4j.appender.roll.layout=org.apache.log4j.PatternLayout
log4j.appender.roll.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS}    %p    %t    %c    %m%n

#继承rootLogger的输出位置
log4j.logger.com.ims = WARN
log4j.logger.org.hibernate.cache = ERROR
log4j.logger.org.directwebremoting = ERROR
#显示sql语句的参数
#log4j.logger.org.hibernate.type=trace 

log4j.logger.jdbc.connection=OFF
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=OFF
log4j.logger.jdbc.sqlonly=OFF
#INFO、OFF
log4j.logger.jdbc.sqltiming=INFO
View Code

  6. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd 
        http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    version="2.4">
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath:applicationContext.xml,
            classpath:applicationContextXxx.xml
    </param-value>
  </context-param>
  
  <listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</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>
      
  <servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:controllerServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
    
  <servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>
View Code

  

六. 类文件介绍

  1. 基础controller类

    功能:设置请求、响应对象;session、cookie操作;ajax访问返回json数据;

    

    1.1. BaseController.java,工程的基础controller类

View Code

    1.2. XxxBaseController.java,子项目的基础controller类:

package com.ims.web.controller.xxx;

import com.ims.web.controller.BaseController;

public class XxxBaseController extends BaseController{
    
}
View Code

  

  2. 基础dao类

    功能:数据库的保存、更新、删除;sql、hql查询;分页查询;调用存储过程

 

    2.1. 工程的基础dao类

      BaseDao.java

package com.ims.persistence.base;

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

import org.hibernate.criterion.DetachedCriteria;

/**
 * 统一数据访问接口
 */
public interface BaseDao<T extends Serializable> {
    
    /**
     * 保存实体对象
     * @param entity 实体对象
     */
    public void save(T entity); 
    
    /**
     * 更新实体对象
     * @param 实体对象
     */
    public void update(T entity);
    
    /**
     * 保存或更新实体对象
     * @param entity 实体对象
     */
    public void saveOrUpdate(T entity);
    
    /**
     * 删除实体对象
     * @param entity 实体对象
     */
    public void delete(T entity);
    
    /**
     * 查询hql语句,返回唯一结果
     * @param hql 
     */
    public Object findUniqueResult(String hql); 
    
    /**
     * 执行sql语句,更新数据库
     * @param sql
     */
    public void updateBySql(String sql);
    
    /**
     * 通过Criteria对象查询,返回实体对象结果集
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集
     */
    public List findByCriteria(DetachedCriteria detachedCriteria);
    
    /**
     * 通过sql语句查询,返回map对象结果集
     * @param sql 
     * @return map对象结果集
     */
    public List<Map<String, Object>> findBySql(String sql);
    
    /**
     * 查询sql语句,返回唯一结果
     * @param sql 
     */
    public Object findUniqueResultBySql(String sql);
    
    /**
     * 通过Criteria对象查询,返回结果集的记录数
     * @param detachedCriteria 离线的Criteria对象
     * @return 结果集的记录数
     */
    public long getCount(DetachedCriteria detachedCriteria);
    
    /**
     * 通过Criteria对象进行分页查询,返回实体对象结果集
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集 
     */
    public List<T> findPage(int pageNum, int pageSize, DetachedCriteria detachedCriteria);
    
    /**
     * 通过sql语句,进行分页查询,返回分页对象
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param sql
     * @return 分页对象
     */
    public Pagination findPage(int pageNum, int pageSize, String sql); // 查找分页对象列表
    
    /**
     * 调用存储过程,返回单结果集
     * @param proceName 存储过程名称
     * @param params 输入参数集合
     * @return map对象结果集
     */
    public List<Map<String, Object>> callProcedure(String proceName, final List<Object> params);
}
View Code

      BaseDaoImpl.java

package com.ims.persistence.base;

import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.jdbc.Work;

public class BaseDaoImpl<T extends Serializable> implements BaseDao<T>{          

    private SessionFactory sessionFactory;
    
    public BaseDaoImpl(){
        super();
    }
    
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }


    /**
     * 返回数据库session对象
     * @return
     */
    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    /**
     * 保存实体对象
     * @param entity 实体对象
     */
    @Override
    public void save(T entity){
        Session session = getSession();
        session.save(entity);        
        session.flush();
        session.evict(entity);
    }
    
    /**
     * 更新实体对象
     * @param 实体对象
     */
    @Override
    public void update(T entity){
        Session session = getSession();
        session.update(entity);        
        session.flush();
        session.evict(entity);
    }
    
    /**
     * 保存或更新实体对象
     * @param entity 实体对象
     */
    @Override
    public void saveOrUpdate(T entity) {        
        Session session = getSession();
        session.saveOrUpdate(entity);        
        session.flush();
        session.evict(entity);    
    }

    /**
     * 删除实体对象
     * @param entity 实体对象
     */
    @Override
    public void delete(T entity){
        Session session = getSession();
        session.delete(entity);        
        session.flush();
        session.evict(entity);
    }    
    
    /**
     * 查询hql语句,返回唯一结果
     * @param hql 
     */
    @Override
    public Object findUniqueResult(String hql){
        Query query = getSession().createQuery(hql);
        return query.uniqueResult();
    }
    
    /**
     * 执行sql语句,更新数据库
     * @param sql
     */
    @Override
    public void updateBySql(final String sql){
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                connection.prepareStatement(sql).executeUpdate();
            }
        });
    }    
    
    /**
     * 通过Criteria对象查询,返回实体对象结果集
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集
     */
    @Override
    public List findByCriteria(DetachedCriteria detachedCriteria){
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        List records = criteria.list();
        return records;
    }
    
    /**
     * 通过sql语句查询,返回map对象结果集
     * @param sql 
     * @return map对象结果集
     */
    @Override
    public List<Map<String, Object>> findBySql(final String sql){
        final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                ResultSet rs = connection.prepareStatement(sql).executeQuery();
                result.addAll(RsHelper.rSToList(rs));
            }
        });
        return result;
    }
    
    /**
     * 查询sql语句,返回唯一结果
     * @param sql 
     */
    @Override
    public Object findUniqueResultBySql(String sql) {    
        return getSession().createSQLQuery(sql.toString()).uniqueResult();
    }
    
    /**
     * 通过Criteria对象查询,返回结果集的记录数
     * @param detachedCriteria 离线的Criteria对象
     * @return 结果集的记录数
     */
    @Override
    public long getCount(DetachedCriteria detachedCriteria) {
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        Object object = criteria.setProjection(Projections.rowCount()).uniqueResult();
        criteria.setProjection(null);
        Long totalRow = Long.valueOf(String.valueOf(object));
        return totalRow;
    }
    
    /**
     * 通过Criteria对象进行分页查询,返回实体对象结果集
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param detachedCriteria 离线的Criteria对象
     * @return 实体对象结果集 
     */
    @Override
    public List<T> findPage(int pageNum, int pageSize, 
            DetachedCriteria detachedCriteria){
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        List<T> records = criteria.setFirstResult((pageNum-1) * pageSize).setMaxResults(pageSize).list();
        return records;
    }
    
    /**
     * 通过sql语句,进行分页查询,返回分页对象
     * @param pageNum 第几页
     * @param pageSize 每页大小
     * @param sql
     * @return 分页对象
     */
    @Override
    public Pagination findPage(final int pageNum, final int pageSize,final String sql){
        final Pagination page = new Pagination();
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                String countSql = MessageFormat.format("select count(*) from ({0}) page", sql);
                ResultSet rs = connection.prepareStatement(countSql).executeQuery();
                page.setTotal(Long.valueOf(RsHelper.getUniqueResult(rs).toString()));
                
                long firstResult = (pageNum - 1)*pageSize;
                String selectSql = MessageFormat.format("select * from ({0}) page limit {1},{2}", sql, firstResult, firstResult+pageSize);
                page.setRows(RsHelper.rSToList(connection.prepareStatement(selectSql).executeQuery()));
            }
        });
        
        return page;
    }
    
    /**
     * 调用存储过程,返回单结果集
     * @param proceName 存储过程名称
     * @param params 输入参数集合
     * @return map对象结果集
     */
    public List<Map<String, Object>> callProcedure(String proceName, final List<Object> params){
        final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        final StringBuffer sql = new StringBuffer();
        sql.append("{call " + proceName + "(");
        for(int i=0; params!=null && i<params.size(); i++){
            sql.append("?");
            if(i+1!=params.size())
                sql.append(",");
        }
        sql.append(")}");
        getSession().doWork(new Work() {   
            @Override
            public void execute(Connection connection) throws SQLException {
                CallableStatement statement = connection.prepareCall(
                        sql.toString());
                for(int i=0; i<params.size(); i++){
                    statement.setObject(i+1, params.get(i));//设置参数
                }

                result.addAll(RsHelper.rSToList(statement.executeQuery()));
            }
        });
        
        return result;
    }
    
}
View Code

      Pagination.java

package com.ims.persistence.base;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页对象,一般用于响应页面请求
 */
public class Pagination {
    /**
     * 总记录数
     */
    private Long total = 0l;
    
    /**
     * 记录集合
     */
    private List rows = new ArrayList();
    
    public Long getTotal() {
        return total;
    }
    public void setTotal(Long total) {
        this.total = total;
    }    
    
    public List getRows() {
        return rows;
    }
    public void setRows(List rows) {
        this.rows = rows;
    }            
}
View Code

      RsHelper.java

package com.ims.persistence.base;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库结果集帮助器
 */
public class RsHelper {
    /**
     * 返回结果集中的唯一结果,没有则返回null
     * @param rs 结果集
     * @return
     * @throws SQLException
     */
    public static Object getUniqueResult(ResultSet rs) throws SQLException{ 
        if(rs.next()) {
            return rs.getObject(1);
        }
        return null;
    }
    
    /**
     * 将实体结果集对象转换为map对象结果集
     * @param rs 实体结果集对象
     * @return map对象结果集
     * @throws SQLException
     */
    public static List<Map<String,Object>> rSToList(ResultSet rs) throws SQLException {   
        if (rs == null)   
            return Collections.EMPTY_LIST;   
        ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息,比如字段数、字段名等   
        int columnCount = md.getColumnCount(); //返回此 ResultSet 对象中的列数   
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();   
        Map<String,Object> rowData = new HashMap<String,Object>();   
        while (rs.next()) {   
            rowData = new HashMap<String,Object>(columnCount);   
            for (int i = 1; i <= columnCount; i++) {   
                rowData.put(md.getColumnLabel(i), rs.getObject(i));   
            }   
            list.add(rowData);   
        }   
        return list;   
    }
}
View Code

    

    2.2. 子项目的基础dao类

      接口类:XxxBaseDao.java

package com.ims.persistence.dao.xxx;

import java.io.Serializable;

import com.ims.persistence.base.BaseDao;

/**
 * 统一数据访问接口
 */
public interface XxxBaseDao<T extends Serializable> extends BaseDao<T> {
    
}
View Code

      实现类:XxxBaseDaoImpl.java

package com.ims.persistence.dao.xxx.impl;

import java.io.Serializable;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;

import com.ims.persistence.base.BaseDaoImpl;
import com.ims.persistence.dao.xxx.XxxBaseDao;

public class XxxBaseDaoImpl<T extends Serializable> extends BaseDaoImpl<T> implements XxxBaseDao<T>{    
    @Resource(name = "xxxSessionFactory")  
    public void setSuperSessionFactory(SessionFactory xxxSessionFactory) {  
        super.setSessionFactory(xxxSessionFactory);  
    }
    
}
View Code


七. 其它文件介绍

  1. basePath.jsp,基础路径设置

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% 
    String path = request.getContextPath(); 
    String basePath = request.getScheme()+"://"+request.getServerName()
        +":"+request.getServerPort()+path+"/"; 
%> 
<base href="<%=basePath%>">
<script type="text/javascript">
    function getRootPath(){
         var strFullPath=window.document.location.href;
         var strPath=window.document.location.pathname;
         var pos=strFullPath.indexOf(strPath);
         var prePath=strFullPath.substring(0,pos);
         var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
         return(prePath+postPath);
    }; 
    var rootPath = getRootPath();
</script>
View Code

 

posted on 2016-12-08 10:28 大饼酥 阅读(...) 评论(...) 编辑 收藏

导航

统计

公告