Maven配置SpringMVC4+Spring4+Hibernate4环境

一、添加依赖

      1、新建maven的web项目后,在pom.xml添加依赖信息,对应的groupId 、artifactId修改成自己新建的

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>web-ssh</groupId>
    <artifactId>moyapp</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>moyapp Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springVersion>4.3.0.RELEASE</springVersion>
        <jacksonVersion>2.9.3</jacksonVersion>
        <hibernateVersion>4.3.5.Final</hibernateVersion>
        <c3p0Version>0.9.5.2</c3p0Version>
        <mysqlVersion>5.1.38</mysqlVersion>
        <slf4jVersion>1.7.21</slf4jVersion>
        <log4jVersion>1.2.17</log4jVersion>
        <jstlVersion>1.2</jstlVersion>
        <servletApiVersion>3.1.0</servletApiVersion>
        <junitVersion>4.12</junitVersion>
    </properties>
    <dependencies>
        <!--junit 测试开始-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junitVersion}</version>
            <scope>test</scope>
        </dependency>
        <!--junit 测试结束-->

        <!--Slf4j + Log4j日志依赖 开始-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4jVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4jVersion}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4jVersion}</version>
        </dependency>
        <!--Slf4j + Log4j日志依赖 结束-->

        <!--JavaEE web容器提供 开始-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servletApiVersion}</version>
            <scope>provided</scope>
        </dependency>
        <!--JavaEE web容器提供 开始-->

        <!--Jsp 常用标签库依赖 开始-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstlVersion}</version>
            <scope>runtime</scope>
        </dependency>
        <!--Jsp 常用标签库依赖 结束-->

        <!-- SpringMVC模块依赖 开始-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jacksonVersion}</version>
        </dependency>
        <!-- SpringMVC模块依赖 结束-->

        <!-- Hibernate模块依赖 开始-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernateVersion}</version>
        </dependency>
        <!-- Hibernate模块依赖 结束-->

        <!--C3p0 数据库连接池依赖 开始-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0Version}</version>
        </dependency>
        <!--C3p0 数据库连接池依赖 结束-->

        <!--Jdbc 驱动依赖 开始 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysqlVersion}</version>
        </dependency>
        <!--Jdbc 驱动依赖 结束 -->

        <!--Spring常用模块依赖 开始-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <!--Spring常用模块依赖结束-->
    </dependencies>
    <build>
        <finalName>moyapp</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8080</port>
                    <charset>${project.build.sourceEncoding}</charset>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>
View Code

      2、个人使用的数据库是mysql,需要新建数据库moyapp

      3、个人的项目信息结构

二、添加配置信息

      1、在修改web.xml信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <!-- *** 初始化Spring容器开始 *** -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  <!-- === 初始化Spring容器结束 === -->

  <!-- *** 初始化SpringMVC开始 *** -->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- === 初始化SpringMVC结束 === -->
</web-app>
View Code

      2、在classpath下添加spring.xml文件,base-package属性值可以改成自己对应的项目基础包名

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- *** 导入外部配置文件开始 *** -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- === 导入外部配置文件结束 === -->

    <context:component-scan base-package="com.moy"/>

    <import resource="spring-mvc.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-tx.xml"/>
    <import resource="spring-task.xml"/>
</beans>  
View Code

      3、在classpath下添加spring-dao.xml,添加数据源配置,packagesToScan列出来的实体类包名可以换成自己的

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- *** dataSource start *** -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- === dataSource end === -->

    <!-- *** sessionFactory start *** -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan">
            <list>
                <value>com.moy.*.*.entity</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            </props>
        </property>
    </bean>
    <!-- === sessionFactory end === -->
</beans>  
View Code

      4、(可选)在classpath下添加spring-task.xml,添加定时任务信息,spring3之后,可以更简单配置定时任务

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task.xsd">

    <task:annotation-driven/>

    <task:scheduled-tasks>
        <task:scheduled ref="testTaskService" method="printCurrentTime" cron="* * * * * ?"/>
    </task:scheduled-tasks>

</beans>  
View Code

      5、在classpath下添加spring-tx.xml,添加事务配置信息,defaultPointcut的包名可以换成自己的

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- *** transactionManager start *** -->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- === transactionManager end === -->

    <!-- *** 配置事务增强处理Bean,指定事务管理器 start *** -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="load*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="list*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="count*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="query*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="execute*" propagation="REQUIRED"/>
            <tx:method name="copy*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- === 配置事务增强处理Bean,指定事务管理器 end === -->

    <!-- *** 配置一个切入点 start *** -->
    <aop:config>
        <aop:pointcut id="defaultPointcut"
                      expression="
                            execution(* com.moy.*.*.dao.*Dao.*(..)) ||
                            execution(* com.moy.*.*.dao.*Support.*(..)) ||
                            execution(* com.moy.*.*.dao.*Service.*(..)) ||
                            execution(* com.moy.*.*.dao.*Impl.*(..)) ||
                            execution(* com.moy.*.*.dao.impl.*impl.*(..)) ||
                            execution(* com.moy.*.*.support.*Support.*(..)) ||
                            execution(* com.moy.*.*.support.*Impl.*(..)) ||
                            execution(* com.moy.*.*.support.impl.*Impl.*(..)) ||
                            execution(* com.moy.*.*.service.*Service.*(..)) ||
                            execution(* com.moy.*.*.service.*Impl.*(..)) ||
                            execution(* com.moy.*.*.service.impl.*Impl.*(..)) "/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="defaultPointcut"/>
    </aop:config>
    <!-- === 配置一个切入点 end === -->

    <!-- *** 开启事务控制的注解支持(不建议使用) start *** -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- === 开启事务控制的注解支持 end === -->
</beans>  
View Code

      6、在classpath下添加spring-mvc.xml,配置spring-mvc信息

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--只扫描@Controller注解类,否则影响事务-->
    <context:component-scan base-package="com.moy" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>  
View Code

      7、在classpath下添加db.properties ,配置数据库连接信息

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/moyapp?useSSL=false
jdbc.username=root
jdbc.password=123
View Code

       8、(可选)在classpath下添加log4j.properties,配置日志信息

### 设置###
log4j.rootLogger=debug,stdout
### 输出信息到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
View Code

三、添加应用代码

      1、新建基础dao类,BaseProjectDao和实现类BaseProjectDao4Impl

package com.moy.moyapp.test.dao;

import org.hibernate.SessionFactory;

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

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/2  <br/>
 * [Description]: hibernate公共dao操作 <br/>
 *
 * @author YeXiangYang
 */
public interface BaseProjectDao {


    /**
     * 获取SessionFactory
     *
     * @return SessionFactory
     */
    SessionFactory getSessionFactory();

    /**
     * 根据ID加载实体
     *
     * @param entityClazz 实体class
     * @param id          唯一主键
     * @return 实体
     */
    <T> T get(Class<T> entityClazz, Serializable id);


    /**
     * 保存实体
     *
     * @param entity 保存的实体
     * @return 实体
     */
    <T> Serializable save(T entity);

    /**
     * 更新实体
     *
     * @param entity 实体
     */
    <T> void update(T entity);

    /**
     * 更新或保持实体
     *
     * @param entity 实体
     */
    <T> void saveOrUpdate(T entity);

    /**
     * 删除实体
     *
     * @param entity 实体
     */
    <T> void delete(T entity);

    /**
     * 根据ID删除实体
     *
     * @param entityClazz 实体class
     * @param id          唯一主键
     */
    <T> int delete(Class<T> entityClazz, Serializable id);

    /**
     * 删除多个实体根据map
     *
     * @param entityClazz
     * @param fieldDeleteMap
     * @param <T>
     */
    <T> int deleteByMap(Class<T> entityClazz, Map<String, Object> fieldDeleteMap);

    /**
     * 获取该实体所有列表
     *
     * @param entityClazz 实体class
     * @return 实体列表
     */
    <T> List<T> listAll(Class<T> entityClazz);

    /**
     * 获取实体列表,根据类字段的map映射成hql的where过滤<br/>
     * <pre>
     * 例如:实体类
     * class A{
     *   String bField;//字段
     * }
     * Map<String, Object> fieldFilterMap = HashMap<>(2);
     * fieldFilterMap.put("bField" , "ABC");
     * findAllByEntity(A.class, Map<String, Object> fieldFilterMap);
     * 则映射成hql为:select en from A en where en.bField='ABC'查询
     * </pre>
     *
     * @param entityClazz    实体class
     * @param fieldFilterMap 根据实体类的字段对应的值进行过滤
     * @return 实体列表
     */
    <T> List<T> listByMap(Class<T> entityClazz, Map<String, Object> fieldFilterMap);

    /**
     * 获取实体总数
     *
     * @param entityClazz 实体class
     * @return 总数
     */
    <T> long countAll(Class<T> entityClazz);

    /**
     * 获取实体总数
     *
     * @param entityClazz
     * @param fieldFilterMap
     * @param <T>
     * @return
     */
    <T> long countByMap(Class<T> entityClazz, Map<String, Object> fieldFilterMap);

    /**
     * 根据HQL语句查询实体
     *
     * @param hql hql语句
     * @return 实体列表
     */
    List<Object> queryByHql(String hql);

    /**
     * 根据带占位符参数HQL语句查询实体
     *
     * @param hql    hql语句,?0的方式设置占位符号
     *               例如:from Entity where id = ?0 and name = ?1
     * @param params 参数
     * @return 数据列表
     */

    List<Object> queryByHql(String hql, Object... params);


    /**
     * 根据带占位符参数HQL语句查询实体
     *
     * @param hql
     * @param map
     * @return
     */
    List<Object> queryByHql(String hql, Map<String, Object> map);

    /**
     * 使用hql 语句进行分页查询操作
     *
     * @param hql      需要查询的hql语句
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @return 当前页的所有记录
     */
    List<Object> queryByHql(String hql, int pageNo, int pageSize);

    /**
     * 使用hql 语句进行分页查询操作
     *
     * @param hql      需要查询的hql语句,?0的方式设置占位符号
     * @param params   如果hql带占位符参数,params用于传入占位符参数
     *                 例如:From Entity where id = ?0
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @return 当前页的所有记录
     */

    List<Object> queryByHql(String hql, int pageNo, int pageSize, Object... params);

    List<Object> queryByHql(String hql, int pageNo, int pageSize, Map<String, Object> params);


    /**
     * 使用sql语句进行查询操作
     *
     * @param sql 需要查询的sql语句
     * @return 返回查询数据
     */
    List<Map<String, Object>> queryBySql(String sql);

    /**
     * 使用sql语句进行查询操作
     *
     * @param sql    需要查询的sql语句,,?0的方式设置占位符号.
     * @param params 如果sql带占位符参数,params用于传入占位符参数
     *               例如:select * from table where id = :index0 and name = :index1
     * @return 返回查询数据
     */
    List<Map<String, Object>> queryBySql(String sql, Object... params);


    /**
     * 使用sql语句进行查询操作
     *
     * @param sql    需要查询的sql语句
     * @param params 如果sql带占位符参数,params用于传入map结构的占位符参数
     * @return 返回查询数据
     */
    List<Map<String, Object>> queryBySql(String sql, Map<String, Object> params);

    /**
     * 使用sql语句进行查询操作
     *
     * @param sql      需要查询的sql语句
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @return 当前页的所有记录
     */
    List<Map<String, Object>> queryBySqlAndPage(String sql, int pageNo, int pageSize);

    /**
     * 使用sql语句进行查询操作
     *
     * @param sql      需要查询的sql语句
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @param params   如果sql带占位符参数,?0的方式设置占位符号
     * @return 当前页的所有记录
     */
    List<Map<String, Object>> queryBySqlAndPage(String sql, int pageNo, int pageSize, Object... params);

    /**
     * 使用sql语句进行查询操作
     *
     * @param sql      需要查询的sql语句
     * @param pageNo   查询第pageNo页的记录
     * @param pageSize 每页需要显示的记录数
     * @param map      如果sql带占位符参数,params用于传入map结构的占位符参数
     * @return 当前页的所有记录
     */
    List<Map<String, Object>> queryBySqlAndPage(String sql, int pageNo, int pageSize, Map<String, Object> map);

    /**
     * 使用sql语句进行查询操作,返回唯一结果
     *
     * @param sql 需要查询的sql语句
     * @return 返回唯一结果
     */
    Object queryUniqueResult(String sql);

    /**
     * 使用sql语句进行查询操作,返回唯一结果
     *
     * @param sql    需要查询的sql语句
     * @param params 如果sql带占位符参数,?0的方式设置占位符号
     * @return 返回唯一结果
     */
    Object queryUniqueResult(String sql, Object... params);

    /**
     * 使用sql语句进行查询操作,返回唯一结果
     *
     * @param sql 需要查询的sql语句
     * @param map 如果sql带占位符参数,传入map作为参数
     * @return 返回唯一结果
     */
    Object queryUniqueResult(String sql, Map<String, Object> map);

    /**
     * 执行hql语句,返回变化的数量
     *
     * @param hql hql语句
     * @return 变化的数量
     */
    int executeHql(String hql);

    /**
     * 执行hql语句,返回变化的数量
     *
     * @param hql    hql语句
     * @param params hql占位符参数,,?0的方式设置占位符号
     * @return 变化的数量
     */
    int executeHql(String hql, Object... params);

    /**
     * 执行hql语句,返回变化的数量
     *
     * @param hql hql语句
     * @param map hql占位符参数,根据map的key和value设置参数
     * @return 变化的数量
     */
    int executeHql(String hql, Map<String, Object> map);

    /**
     * 执行sql语句,返回变化的数量
     *
     * @param sql sql语句
     * @return 变化的数量
     */
    int executeSql(String sql);

    /**
     * 执行sql语句,返回变化的数量
     *
     * @param sql    sql语句
     * @param params hql占位符参数,,?0的方式设置占位符号
     * @return 变化的数量
     */
    int executeSql(String sql, Object... params);

    /**
     * 执行sql语句,返回变化的数量
     *
     * @param sql sql语句
     * @param map hql占位符参数,根据map的key和value设置参数
     * @return 变化的数量
     */
    int executeSql(String sql, Map<String, Object> map);

}
View Code
package com.moy.moyapp.test.dao.impl;

import com.moy.moyapp.test.dao.BaseProjectDao;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/2  <br/>
 * [Description]: hibernate公共dao操作 <br/>
 *
 * @author YeXiangYang
 */
@Repository("baseProjectDao")
public class BaseProjectDao4Impl implements BaseProjectDao {

    private static final Object[] EMPTY_OBJECT_ARRAY = {};
    private static final Map<String, Object> EMPTY_MAP = Collections.EMPTY_MAP;

    @Resource
    private SessionFactory sessionFactory;

    @Override
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T get(Class<T> entityClazz, Serializable id) {
        return (T) getSession().get(entityClazz, id);
    }


    @Override
    public <T> Serializable save(T entity) {
        return getSession().save(entity);
    }

    @Override
    public <T> void update(T entity) {
        getSession().update(entity);
    }

    public <T> void saveOrUpdate(T entity) {
        getSession().saveOrUpdate(entity);
    }

    @Override
    public <T> void delete(T entity) {
        getSession().delete(entity);
    }

    @Override
    public <T> int delete(Class<T> entityClazz, Serializable id) {
        Map<String, Object> fieldFilterMap = new HashMap<>(2);
        fieldFilterMap.put("id", id);
        return deleteByMap(entityClazz, fieldFilterMap);
    }

    @Override
    public <T> int deleteByMap(Class<T> entityClazz, Map<String, Object> fieldDeleteMap) {

        StringBuilder sb = buildHql("DELETE ", entityClazz.getSimpleName(), " en WHERE 1 = 1 ");

        appendEqualsCondition(fieldDeleteMap, sb);

        Query query = getSession().createQuery(sb.toString());

        setParamsByMap(fieldDeleteMap, query);

        return query.executeUpdate();

    }

    /**
     * 追加equals条件
     *
     * @param fieldFilterMap 类字段参数map
     * @param sb             hql语句
     */
    private void appendEqualsCondition(Map<String, Object> fieldFilterMap, StringBuilder sb) {
        if (null != fieldFilterMap) {
            for (Map.Entry<String, Object> en : fieldFilterMap.entrySet()) {
                String key = en.getKey().trim();
                sb.append(" and en.").append(key);
                sb.append(" = :").append(key);
            }
        }
    }

    @Override
    public <T> List<T> listAll(Class<T> entityClazz) {
        return listByMap(entityClazz, EMPTY_MAP);
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> listByMap(Class<T> entityClazz, Map<String, Object> fieldFilterMap) {

        StringBuilder sb = buildHql("FROM ", entityClazz.getSimpleName(), " en WHERE 1 = 1 ");

        appendEqualsCondition(fieldFilterMap, sb);

        Query query = getSession().createQuery(sb.toString());

        setParamsByMap(fieldFilterMap, query);

        return (List<T>) query.list();
    }

    @Override
    public <T> long countAll(Class<T> entityClazz) {
        return countByMap(entityClazz, null);
    }

    @Override
    public <T> long countByMap(Class<T> entityClazz, Map<String, Object> fieldFilterMap) {

        StringBuilder sb = buildHql("SELECT COUNT(*) FROM ", entityClazz.getSimpleName(), " en WHERE 1 = 1 ");

        appendEqualsCondition(fieldFilterMap, sb);

        List<?> l = queryByHql(sb.toString(), fieldFilterMap);

        if (null != l && 1 == l.size()) {
            return (Long) l.get(0);
        }
        return 0;
    }

    @Override
    public List<Object> queryByHql(String hql) {
        return queryByHql(hql, EMPTY_OBJECT_ARRAY);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Object> queryByHql(String hql, Object... params) {

        Query query = getSession().createQuery(hql);

        setParamsByArray(query, params);

        return query.list();
    }

    @Override
    public List<Object> queryByHql(String hql, Map<String, Object> map) {
        Query query = getSession().createQuery(hql);

        setParamsByMap(map, query);

        return query.list();
    }

    @Override
    public List<Object> queryByHql(String hql, int pageNo, int pageSize) {
        return queryByHql(hql, pageNo, pageSize, EMPTY_OBJECT_ARRAY);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Object> queryByHql(String hql, int pageNo, int pageSize, Object... params) {

        Query query = getSession().createQuery(hql);

        setPageParam(pageNo, pageSize, query);

        setParamsByArray(query, params);

        return (List<Object>) query.list();
    }

    @Override
    public List<Object> queryByHql(String hql, int pageNo, int pageSize, Map<String, Object> params) {

        Query query = getSession().createQuery(hql);

        setPageParam(pageNo, pageSize, query);

        setParamsByMap(params, query);

        return (List<Object>) query.list();
    }


    @Override
    public List<Map<String, Object>> queryBySql(String sql) {
        return queryBySql(sql, EMPTY_OBJECT_ARRAY);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, Object>> queryBySql(String sql, Object... params) {

        SQLQuery sqlQuery = getSession().createSQLQuery(sql);

        sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        setParamsByArray(sqlQuery, params);

        return (List<Map<String, Object>>) sqlQuery.list();
    }

    public List<Map<String, Object>> queryBySql(String sql, Map<String, Object> map) {

        SQLQuery sqlQuery = getSession().createSQLQuery(sql);

        sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        setParamsByMap(map, sqlQuery);

        return (List<Map<String, Object>>) sqlQuery.list();
    }


    @Override
    public List<Map<String, Object>> queryBySqlAndPage(String sql, int pageNo, int pageSize) {
        return queryBySqlAndPage(sql, pageNo, pageSize, EMPTY_OBJECT_ARRAY);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, Object>> queryBySqlAndPage(String sql, int pageNo, int pageSize, Object... params) {

        SQLQuery sqlQuery = getSession().createSQLQuery(sql);

        sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        setPageParam(pageNo, pageSize, sqlQuery);

        setParamsByArray(sqlQuery, params);

        return (List<Map<String, Object>>) sqlQuery.list();
    }

    public List<Map<String, Object>> queryBySqlAndPage(String sql, int pageNo, int pageSize, Map<String, Object> map) {

        SQLQuery sqlQuery = getSession().createSQLQuery(sql);

        sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        setPageParam(pageNo, pageSize, sqlQuery);

        setParamsByMap(map, sqlQuery);

        return (List<Map<String, Object>>) sqlQuery.list();
    }

    @Override
    public Object queryUniqueResult(String sql) {
        return queryUniqueResult(sql, EMPTY_OBJECT_ARRAY);
    }

    @Override
    public Object queryUniqueResult(String sql, Object... params) {

        SQLQuery sqlQuery = getSession().createSQLQuery(sql);

        setParamsByArray(sqlQuery, params);

        return sqlQuery.uniqueResult();
    }

    @Override
    public Object queryUniqueResult(String sql, Map<String, Object> map) {

        SQLQuery sqlQuery = getSession().createSQLQuery(sql);

        setParamsByMap(map, sqlQuery);

        return sqlQuery.uniqueResult();
    }

    @Override
    public int executeHql(String hql) {

        return executeHql(hql, EMPTY_OBJECT_ARRAY);
    }

    @Override
    public int executeHql(String hql, Object... params) {

        Query query = getSession().createQuery(hql);

        setParamsByArray(query, params);

        return query.executeUpdate();
    }

    @Override
    public int executeHql(String hql, Map<String, Object> map) {

        Query query = getSession().createQuery(hql);

        setParamsByMap(map, query);

        return query.executeUpdate();
    }

    @Override
    public int executeSql(String sql) {

        return executeSql(sql, EMPTY_OBJECT_ARRAY);
    }

    @Override
    public int executeSql(String sql, Object... params) {

        Query query = getSession().createSQLQuery(sql);

        setParamsByArray(query, params);

        return query.executeUpdate();
    }

    @Override
    public int executeSql(String sql, Map<String, Object> map) {

        Query query = getSession().createSQLQuery(sql);

        setParamsByMap(map, query);

        return query.executeUpdate();
    }

    /**
     * 根据数组设置org.hibernate.Query查询参数,?0的方式设置占位符号
     *
     * @param query org.hibernate.Query
     * @param array 数组
     */
    private void setParamsByArray(Query query, Object[] array) {
        if (null != array) {
            for (int i = 0, len = array.length; i < len; i++) {
                query.setParameter(String.valueOf(i), array[i]);
            }
        }
    }

    private StringBuilder buildHql(String keyword, String className, String where) {
        StringBuilder sb = new StringBuilder(keyword);
        sb.append(className).append(where);
        return sb;
    }

    /**
     * 设置分页参数
     *
     * @param pageNo   第几页
     * @param pageSize 每页多少数目
     * @param query    org.hibernate.Query
     */
    private void setPageParam(int pageNo, int pageSize, Query query) {
        query.setFirstResult((pageNo - 1) * pageSize);
        query.setMaxResults(pageSize);
    }

    /**
     * 根据map的key和value设置org.hibernate.Query查询参数
     *
     * @param map   map
     * @param query org.hibernate.Query
     */
    private void setParamsByMap(Map<String, Object> map, Query query) {

        if (null != query && null != map && map.size() > 0) {
            for (Map.Entry<String, Object> each : map.entrySet()) {
                String key = each.getKey();
                Object value = each.getValue();
                if (null == value) {
                    query.setParameter(key, value);
                } else if (value.getClass().isArray()) {
                    query.setParameterList(key, (Object[]) value);
                } else if (value instanceof Collection) {
                    query.setParameterList(key, (Collection) value);
                } else {
                    query.setParameter(key, value);
                }
            }
        }
    }
}
View Code

       2、新建实体类TestEntity  

package com.moy.moyapp.test.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/2  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@Entity
@Table(name = "t_test")
public class TestEntity implements Serializable {

    private static final long serialVersionUID = 8530202658667667146L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "gtm_create")
    private Date gtmCreate;
    @Column(name = "gtm_modified")
    private Date gtmModified;
    @Column(name = "description")
    private String desc;

    public TestEntity() {
    }

    public static TestEntity createInstance() {
        TestEntity test = new TestEntity();
        test.setGtmCreate(new Date());
        test.setGtmModified(new Date());
        test.setDesc("测试数据描述:[" + UUID.randomUUID() + "]");
        return test;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getGtmCreate() {
        return gtmCreate;
    }

    public void setGtmCreate(Date gtmCreate) {
        this.gtmCreate = gtmCreate;
    }

    public Date getGtmModified() {
        return gtmModified;
    }

    public void setGtmModified(Date gtmModified) {
        this.gtmModified = gtmModified;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "TestEntity{" +
                "id=" + id +
                ", gtmCreate=" + gtmCreate +
                ", gtmModified=" + gtmModified +
                ", desc='" + desc + '\'' +
                '}';
    }
}
View Code

       3、新建基础服务类BaseProjectService和实现类BaseProjectServiceImpl

package com.moy.moyapp.test.service;


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

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/2  <br/>
 * [Description]: 简化操作,项目基础Service类 <br/>
 *
 * @author YeXiangYang
 */
public interface BaseProjectService<E> {

    /**
     * 保存
     */
    Serializable save(E entity);

    /**
     * 删除根据id
     */
    int delete(Serializable id);

    /**
     * 删除根据map条件
     */
    int deleteByMap(Map<String, Object> fieldFilterMap);

    /**
     * 删除
     */
    void delete(E entity);

    /**
     * 删除根据实体类
     */
    void update(E entity);

    /**
     * 保存或者更新
     */
    void saveOrUpdate(E entity);

    /**
     * 查询根据id
     */
    E get(Serializable id);

    /**
     * 查询所有
     */
    List<E> listAll();

    /**
     * 查询根据map条件
     */
    List<E> listByMap(Map<String, Object> fieldFilterMap);

    /**
     * 查询个数
     */
    long countAll();

    /**
     * 查询个数根据map条件
     */
    long countByMap(Map<String, Object> fieldFilterMap);
}
View Code
package com.moy.moyapp.test.service.impl;


import com.moy.moyapp.test.dao.BaseProjectDao;
import com.moy.moyapp.test.service.BaseProjectService;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/2  <br/>
 * [Description]: 简化操作,项目基础Service类 <br/>
 *
 * @author YeXiangYang
 */
public abstract class BaseProjectServiceImpl<E> implements BaseProjectService<E> {

    @Resource
    protected BaseProjectDao baseProjectDao;

    protected final Class<E> clazz;

    {
        try {
            ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
            clazz = (Class<E>) parameterizedType.getActualTypeArguments()[0];
        } catch (Exception e) {
            throw new RuntimeException("未声明实体泛型,继承BaseService需要按照规范!!!");
        }
    }

    @Override
    public Serializable save(E entity) {
        return baseProjectDao.save(entity);
    }

    @Override
    public int delete(Serializable id) {
        return baseProjectDao.delete(clazz, id);
    }

    @Override
    public int deleteByMap(Map<String, Object> fieldFilterMap) {
        return baseProjectDao.deleteByMap(clazz, fieldFilterMap);
    }

    @Override
    public void delete(E entity) {
        baseProjectDao.delete(entity);
    }

    @Override
    public void update(E entity) {
        baseProjectDao.update(entity);
    }

    @Override
    public void saveOrUpdate(E entity) {
        baseProjectDao.saveOrUpdate(entity);
    }

    @Override
    public E get(Serializable id) {
        return baseProjectDao.get(clazz, id);
    }

    @Override
    public List<E> listAll() {
        return baseProjectDao.listAll(clazz);
    }

    @Override
    public List<E> listByMap(Map<String, Object> fieldFilterMap) {
        return baseProjectDao.listByMap(clazz, fieldFilterMap);
    }

    @Override
    public long countAll() {
        return baseProjectDao.countAll(clazz);
    }

    @Override
    public long countByMap(Map<String, Object> fieldFilterMap) {
        return baseProjectDao.countByMap(clazz, fieldFilterMap);
    }
}
View Code

       4、新建操作实体TestEntity的服务类TestService,和实现类TestServiceImpl

package com.moy.moyapp.test.service;


import com.moy.moyapp.test.entity.TestEntity;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/4  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public interface TestService extends BaseProjectService<TestEntity> {

    void saveTxTest();
}
View Code
package com.moy.moyapp.test.service.impl;

import com.moy.moyapp.test.entity.TestEntity;
import com.moy.moyapp.test.service.TestService;
import org.springframework.stereotype.Service;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/4  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@Service
public class TestServiceImpl extends BaseProjectServiceImpl<TestEntity> implements TestService {

    @Override
    public void saveTxTest() {
        TestEntity instance = TestEntity.createInstance();
        instance.setDesc("在事务下,我保存不上");
        save(instance);
        int i = 1 / 0;
    }
}
View Code

       5、(可选)新建定时任务测试类TestTaskServiceImpl

package com.moy.moyapp.test.task;

import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/6  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@Component("testTaskService")
public class TestTaskServiceImpl {

    public void printCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(new Date()));
    }
}
View Code

      6、新建TestController

package com.moy.moyapp.test.controller;

import com.moy.moyapp.test.entity.TestEntity;
import com.moy.moyapp.test.service.TestService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/4  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */

@Controller
@RequestMapping("/test")
public class TestController {

    @Resource
    TestService testService;

    @RequestMapping("/save")
    @ResponseBody
    public Serializable save(HttpServletRequest request, HttpServletResponse response) {
        TestEntity instance = TestEntity.createInstance();
        return testService.save(instance);
    }
    
    @ResponseBody
    @RequestMapping("/saveTxTest")
    public String saveTxTest(HttpServletRequest request, HttpServletResponse response) {
        try {
            testService.saveTxTest();
        } catch (Exception e) {
            return e.getMessage();
        }
        return "success";
    }
}
View Code

      7、在WEB-INF同级目录添加index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Test</title>
</head>
<%
    String contextPath = request.getContextPath();
%>
<body>
<a href="<%=contextPath%>/test/save.do">save</a><br/>
<a href="<%=contextPath%>/test/saveTxTest.do">saveTxTest</a><br/>
</body>
</html>
View Code

四、测试

     1、测试dao类BaseProjectDao4ImplTest

package com.moy.moyapp.test.dao.impl;

import com.moy.moyapp.test.dao.BaseProjectDao;
import com.moy.moyapp.test.entity.TestEntity;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/3  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
public class BaseProjectDao4ImplTest {

    @Resource
    BaseProjectDao baseProjectDao;
    Logger logger = LoggerFactory.getLogger(getClass());
    long beforeTime;
    long afterTime;

    @Before
    public void before() {
        logger.info(this.toString());
        beforeTime = System.currentTimeMillis();
        logger.info("test method before : {}ms", beforeTime);
    }

    @After
    public void After() {
        afterTime = System.currentTimeMillis();
        logger.info("test method After : {}ms", afterTime);
        logger.info("total time : {}ms", afterTime - beforeTime);
    }

    @Test
    public void getSessionFactory() {
        SessionFactory sessionFactory = baseProjectDao.getSessionFactory();
        logger.info(sessionFactory.toString());
    }

    @Test
    public void getTest() {
        TestEntity saveEntity = TestEntity.createInstance();
        logger.info(saveEntity.toString());
        Serializable save = baseProjectDao.save(saveEntity);
        logger.info(save.toString());
        TestEntity testEntity = baseProjectDao.get(TestEntity.class, saveEntity.getId());
        logger.info(testEntity.toString());
    }

    @Test
    public void saveTest() {
        TestEntity test = TestEntity.createInstance();
        baseProjectDao.save(test);
    }


    @Test
    public void updateTest() {
        TestEntity testEntity = TestEntity.createInstance();
        logger.info(testEntity.toString());
        logger.info(baseProjectDao.save(testEntity).toString());
        testEntity.setGtmModified(null);
        testEntity.setDesc("修改后");
        baseProjectDao.update(testEntity);
    }

    @Test
    public void saveOrUpdateTest() {
        TestEntity testEntity = TestEntity.createInstance();
        baseProjectDao.saveOrUpdate(testEntity);

        testEntity.setDesc("保存或修改");
        baseProjectDao.saveOrUpdate(testEntity);
    }

    @Test
    public void deleteTest() {

        TestEntity testEntity = TestEntity.createInstance();
        Serializable id = baseProjectDao.save(testEntity);

        logger.info("" + baseProjectDao.delete(TestEntity.class, id));

        baseProjectDao.save(testEntity);
        baseProjectDao.delete(testEntity);
    }

    @Test
    public void deleteByMapTest() {
        TestEntity testEntity = TestEntity.createInstance();
        baseProjectDao.save(testEntity);
        HashMap param = new HashMap();
        param.put("desc", testEntity.getDesc());
        logger.info(String.valueOf(baseProjectDao.deleteByMap(TestEntity.class, param)));
    }

    @Test
    public void listAllTest() {
        List<TestEntity> list = baseProjectDao.listAll(TestEntity.class);
        printList(list);
    }

    @Test
    public void listByMapTest() {
        TestEntity testEntity = TestEntity.createInstance();
        baseProjectDao.save(testEntity);

        Map param = new HashMap();
        param.put("desc", testEntity.getDesc());

        List<TestEntity> list = baseProjectDao.listByMap(TestEntity.class, param);
        printList(list);
    }

    private void printList(List list) {
        if (null != list) {
            for (Object each : list) {
                logger.info(each.toString());
            }
        }
    }

    @Test
    public void countAllTest() {
        long count = baseProjectDao.countAll(TestEntity.class);
        logger.info(String.valueOf(count));
    }

    @Test
    public void countByMapTest() {
        TestEntity testEntity = TestEntity.createInstance();
        baseProjectDao.save(testEntity);

        Map param = new HashMap();
        param.put("desc", testEntity.getDesc());

        long count = baseProjectDao.countByMap(TestEntity.class, param);
        logger.info(String.valueOf(count));
    }

    @Test
    public void queryByHqlTest() {
        String hql = "from TestEntity";

        List<Object> list = baseProjectDao.queryByHql(hql);
        printList(list);

        TestEntity testEntity = TestEntity.createInstance();
        Serializable id = baseProjectDao.save(testEntity);

        String hqlByListParam = hql + " where id = ?0";
        Object[] objects = {id};
        List<Object> hqlByListParamList = baseProjectDao.queryByHql(hqlByListParam, objects);
        printList(hqlByListParamList);

        List<Object> hqlByListParamListPage = baseProjectDao.queryByHql(hqlByListParam, 0, 5, objects);
        printList(hqlByListParamListPage);


        String hqlByListMap = hql + " where id = :id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        List<Object> hqlByListMapList = baseProjectDao.queryByHql(hqlByListMap, param);
        printList(hqlByListMapList);

        List<Object> hqlByListMapListPage = baseProjectDao.queryByHql(hqlByListMap, 0, 5, param);
        printList(hqlByListMapListPage);
    }


    @Test
    public void queryBySqlTest() {
        String sql = "select * from t_test";

        List<Map<String, Object>> list = baseProjectDao.queryBySql(sql);
        printList(list);

        TestEntity testEntity = TestEntity.createInstance();
        Serializable id = baseProjectDao.save(testEntity);

        String sqlByListParam = sql + " where id = ?0";
        Object[] objects = {id};
        List<Map<String, Object>> sqlByListParamList = baseProjectDao.queryBySql(sqlByListParam, objects);
        printList(sqlByListParamList);

        List<Map<String, Object>> sqlByListParamListPage = baseProjectDao.queryBySqlAndPage(sqlByListParam, 0, 5, objects);
        printList(sqlByListParamListPage);

        String sqlByListMap = sql + " where id = :id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        List<Map<String, Object>> sqlByListMapList = baseProjectDao.queryBySql(sqlByListMap, param);
        printList(sqlByListMapList);

        List<Map<String, Object>> sqlByListMapListPage = baseProjectDao.queryBySqlAndPage(sqlByListMap, 0, 5, param);
        printList(sqlByListMapListPage);
    }


    @Test
    public void queryUniqueResultTest() {
        String sql = "select count(*) from t_test";

        TestEntity testEntity = TestEntity.createInstance();
        Serializable id = baseProjectDao.save(testEntity);
        Object count = baseProjectDao.queryUniqueResult(sql);

        logger.info(String.valueOf(count));

        String sqlByListParam = sql + " where id = ?0";
        Object countByListParam = baseProjectDao.queryUniqueResult(sqlByListParam, new Object[]{id});
        logger.info(String.valueOf(countByListParam));

        String sqlByListMap = sql + " where id = :id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        Object countByMapCount = baseProjectDao.queryUniqueResult(sqlByListMap, param);
        logger.info(String.valueOf(countByMapCount));
    }

    @Test
    public void executeHqlTest() {
        String hql = "delete TestEntity ";
        TestEntity testEntity = TestEntity.createInstance();
        baseProjectDao.save(testEntity);

        Object count = baseProjectDao.executeHql(hql);
        logger.info(String.valueOf(count));

        Serializable id = baseProjectDao.save(testEntity);
        String hqlByListParam = hql + " where id = ?0";
        int countByList = baseProjectDao.executeHql(hqlByListParam, new Object[]{id});
        logger.info(String.valueOf(countByList));

        id = baseProjectDao.save(testEntity);
        String hqlByMapParam = hql + " where id = :id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        int countByMap = baseProjectDao.executeHql(hqlByMapParam, param);
        logger.info(String.valueOf(countByMap));
    }

    @Test
    public void executeSqlTest() {
        String sql = "delete from t_test ";
        TestEntity testEntity = TestEntity.createInstance();
        baseProjectDao.save(testEntity);

        Object count = baseProjectDao.executeSql(sql);
        logger.info(String.valueOf(count));

        Serializable id = baseProjectDao.save(testEntity);
        String hqlByListParam = sql + " where id = ?0";
        int countByList = baseProjectDao.executeSql(hqlByListParam, new Object[]{id});
        logger.info(String.valueOf(countByList));

        id = baseProjectDao.save(testEntity);
        String hqlByMapParam = sql + " where id = :id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        int countByMap = baseProjectDao.executeSql(hqlByMapParam, param);
        logger.info(String.valueOf(countByMap));
    }
}
View Code

      2、测试service类TestServiceImplTest

package com.moy.moyapp.test.service.impl;

import com.moy.moyapp.test.entity.TestEntity;
import com.moy.moyapp.test.service.TestService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/6  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
public class TestServiceImplTest {
    @Resource
    TestService testService;
    Logger logger = LoggerFactory.getLogger(getClass());
    long beforeTime;
    long afterTime;

    @Before
    public void before() {
        logger.info(this.toString());
        beforeTime = System.currentTimeMillis();
        logger.info("test method before : {}ms", beforeTime);
    }

    @After
    public void After() {
        afterTime = System.currentTimeMillis();
        logger.info("test method After : {}ms", afterTime);
        logger.info("total time : {}ms", afterTime - beforeTime);
    }

    @Test
    public void saveTest() {
        TestEntity entity = TestEntity.createInstance();
        logger.info(testService.save(entity).toString());
    }

    @Test
    public void deleteTest() {
        TestEntity entity = TestEntity.createInstance();
        Serializable id = testService.save(entity);
        logger.info(String.valueOf(testService.delete(id)));

        logger.info(String.valueOf(testService.save(entity)));
        testService.delete(entity);
    }

    @Test
    public void deleteByMapTest() {
        TestEntity entity = TestEntity.createInstance();
        Serializable id = testService.save(entity);

        HashMap<String, Object> param = new HashMap<>();
        param.put("id", id);

        logger.info(String.valueOf(testService.deleteByMap(param)));

        testService.save(entity);
        testService.delete(entity);

        id = testService.save(entity);
        testService.delete(id);
    }


    @Test
    public void updateTest() {
        TestEntity entity = TestEntity.createInstance();
        testService.save(entity);
        entity.setDesc(null);
        testService.update(entity);
    }

    @Test
    public void saveOrUpdateTest() {
        TestEntity entity = TestEntity.createInstance();
        testService.saveOrUpdate(entity);
        entity.setDesc(null);
        testService.saveOrUpdate(entity);
    }

    @Test
    public void getTest() {
        TestEntity entity = TestEntity.createInstance();
        Serializable id = testService.save(entity);
        TestEntity testEntity = testService.get(id);
        logger.info(testEntity.toString());
    }

    @Test
    public void listAllTest() {
        List<TestEntity> list = testService.listAll();
        printList(list);
    }

    @Test
    public void listByMapTest() {
        TestEntity entity = TestEntity.createInstance();
        testService.save(entity);

        Map<String, Object> param = new HashMap<>();
        param.put("desc", entity.getDesc());

        List<TestEntity> list = testService.listByMap(param);
        printList(list);
    }

    @Test
    public void countAllTest() {
        TestEntity entity = TestEntity.createInstance();
        testService.save(entity);

        logger.info(String.valueOf(testService.countAll()));
    }

    @Test
    public void countByMapTest() {
        TestEntity entity = TestEntity.createInstance();
        testService.save(entity);

        Map<String, Object> param = new HashMap<>();
        param.put("id", entity.getId());

        logger.info(String.valueOf(testService.countByMap(param)));
    }

    @Test
    public void saveTxTest() {
        try {
            testService.saveTxTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void printList(List list) {
        if (null != list) {
            for (Object each : list) {
                logger.info(each.toString());
            }
        }
    }
}
View Code

      3、运行tomcat7插件后,打开浏览器,输入127.0.0.1:8080/moyapp测试接口和事务接口。

 

yexiangyang

moyyexy@gmail.com


 

 

posted @ 2018-03-07 10:22  墨阳  阅读(1055)  评论(0编辑  收藏  举报