Maven配置SpringMVC4+Spring4+Mybatis3环境

一、添加依赖

      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-ssm</groupId>
  <artifactId>whymoy</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>whymoy 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>
    <mybatisVersion>3.4.4</mybatisVersion>
    <mybatisSpringVersion>1.3.0</mybatisSpringVersion>
    <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模块依赖 结束-->

    <!-- Mybatis模块依赖 开始-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatisVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatisSpringVersion}</version>
    </dependency>
    <!-- Mybatis模块依赖 结束-->

    <!--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>whymoy</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,需要新建数据库whymoy,初始化sql语句

CREATE TABLE t_test (
  id int(11) NOT NULL AUTO_INCREMENT,
  description varchar(255) DEFAULT NULL,
  gtm_create datetime DEFAULT NULL,
  gtm_modified datetime DEFAULT NULL,
  PRIMARY KEY (id)
)
View Code

      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: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">

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

    <!-- *** 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 === -->

    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--&lt;!&ndash; 扫描entity包 使用别名 &ndash;&gt;-->
        <!--<property name="typeAliasesPackage" value="com.moy..test.entity"/>-->
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <!-- 配置转换器,对于在basePackage设置的包(包括子包)下的接口类的全类名,
        如果在Mapper.xml文件中定义过命名空间,
        将被转换成spring的BEAN,在调用 的地方通过@Autowired方式将可以注入接口实例-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.moy.*.*.mapper"/>
    </bean>
</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: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/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.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></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.*.*.mapper.*Dao.*(..)) ||
                            execution(* com.moy.*.*.mapper.*Support.*(..)) ||
                            execution(* com.moy.*.*.mapper.*Service.*(..)) ||
                            execution(* com.moy.*.*.mapper.*Impl.*(..)) ||
                            execution(* com.moy.*.*.mapper.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: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.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.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/whymoy?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

        9、在classpath下添加mybatis-config.xml,添加mybatis配置信息,package包名可以换成自己的

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.moy.whymoy.test.entity"/>
    </typeAliases>
</configuration>
View Code

三、添加应用代码

      1、新建基础dao类BaseDao和继承接口TestDao

package com.moy.whymoy.test.mapper;


import java.util.List;

/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/11/21  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
public interface BaseDao<T> {

    Integer insert(T entity);

    Integer delete(T entity);

    Integer update(T entity);

    List<T> select(T entity);

    Integer count(T entity);
}
View Code
package com.moy.whymoy.test.mapper;

import com.moy.whymoy.test.entity.TestEntity;
import org.springframework.stereotype.Repository;

/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/11/20  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
@Repository
public interface TestDao extends BaseDao<TestEntity> {
}
View Code

      2、在mapper目录下,新建TestDao的配置文件TestMapper.xml,mybatis通过接口名映射,可以主动在spring容器中添加动态代理实现类

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.moy.whymoy.test.mapper.TestDao">
    <!-- type指定的是对应的实体类 -->
    <resultMap type="testEntity" id="testResultMap">
        <!-- id用来配置表的主键与类的属性的映射关系 ,column指定的是表的字段名; property指定的是类的属性名-->
        <id column="id" property="id"/>
        <!-- result用来配置 普通字段与类的属性的映射关系 ,column指定的是表的字段名; property指定的是类的属性名-->
        <result column="gtm_create" property="gtmCreate"/>
        <result column="gtm_modified" property="gtmModified"/>
        <result column="description" property="desc"/>
    </resultMap>
    <insert id="insert"  keyProperty="id" parameterType="testEntity">
        insert into t_test(gtm_create,description) values(#{gtmCreate},#{desc})
    </insert>

    <delete id="delete" parameterType="testEntity">
        delete from t_test WHERE id=#{id}
    </delete>

    <update id="update" parameterType="testEntity">
        update  t_test set description=#{desc},gtm_create=#{gtmCreate} WHERE id=#{id}
    </update>

    <select id="select" parameterType="testEntity" resultMap="testResultMap">
        select * from t_test
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="gtmCreate != null">
                and gtm_create like #{gtmCreate}
            </if>
            <if test="desc != null">
                and description like #{desc}
            </if>
        </where>
    </select>

    <select id="count" parameterType="testEntity" resultType="integer">
        select count(0) from t_test
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="gtmCreate != null">
                and gtm_create like #{gtmCreate}
            </if>
            <if test="desc != null">
                and description like #{desc}
            </if>
        </where>
    </select>
</mapper>
View Code

      3、 新建实体类TestEntity

package com.moy.whymoy.test.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/10/27  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
public class TestEntity implements Serializable {


    private static final long serialVersionUID = 8530202658667667146L;
    private Integer id;
    private Date gtmCreate;
    private Date gtmModified;
    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、新建基础服务类BaseService和基础实现类BaseServiceImpl

package com.moy.whymoy.test.service;


import java.util.List;

/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/11/21  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
public interface BaseService<T> {

    //保存
    Integer insert(T entity);

    //删除
    Integer delete(T entity);

    //更新
    Integer update(T entity);

    //查询
    List<T> select(T entity);

    //计数
    Integer count(T entity);
}
View Code
package com.moy.whymoy.test.service.impl;

import com.moy.whymoy.test.mapper.BaseDao;
import com.moy.whymoy.test.mapper.TestDao;
import com.moy.whymoy.test.service.BaseService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/11/29  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
public abstract class BaseServiceImpl<T> implements BaseService<T> {

    @Resource
    protected TestDao testDao;
    protected BaseDao<T> baseDao;

    public static String ENTITY_NORM_SUFFIX = "Entity";

    @PostConstruct
    private void initBaseDao() {
        try {
            Class<? extends BaseServiceImpl> subClass = this.getClass();
            Class<?> superClass = subClass.getSuperclass();

            ParameterizedType type = (ParameterizedType) subClass.getGenericSuperclass();
            Class<T> clazz = (Class<T>) type.getActualTypeArguments()[0];

            String classSimpleName = clazz.getSimpleName();
            if (classSimpleName.lastIndexOf(ENTITY_NORM_SUFFIX) > 0) {
                classSimpleName = classSimpleName.substring(0, classSimpleName.lastIndexOf(ENTITY_NORM_SUFFIX)) + "Dao";
                String fieldName = classSimpleName.substring(0, 1).toLowerCase() + classSimpleName.substring(1);
                Field currentField = superClass.getDeclaredField(fieldName);
                Field baseField = superClass.getDeclaredField("baseDao");
                baseField.set(this, currentField.get(this));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Integer insert(T entity) {
        return baseDao.insert(entity);
    }

    @Override
    public Integer delete(T entity) {
        return baseDao.delete(entity);
    }

    @Override
    public Integer update(T entity) {
        return baseDao.update(entity);
    }

    @Override
    public List<T> select(T entity) {
        return baseDao.select(entity);
    }

    @Override
    public Integer count(T entity) {
        return baseDao.count(entity);
    }
}
View Code

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

package com.moy.whymoy.test.service;


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

/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/11/20  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
public interface TestService extends BaseService<TestEntity> {

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


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


/**
 * Project:web  <br/>
 * Description:  <br/>
 * Date:2017/11/20  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
@Service("testService")
public class TestServiceImpl extends BaseServiceImpl<TestEntity> implements TestService {
    @Override
    public void saveTxTest() {
        TestEntity instance = TestEntity.createInstance();
        instance.setDesc("在事务下,我保存不上");
        insert(instance);
        int i = 1 / 0;
    }
}
View Code

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

package com.moy.whymoy.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.whymoy.test.controller;

import com.moy.whymoy.test.entity.TestEntity;
import com.moy.whymoy.test.service.TestService;
import org.springframework.stereotype.Controller;
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:web  <br/>
 * Description:  <br/>
 * Date:2017/11/20  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Resource
    private TestService testService;

    @RequestMapping("/save")
    public void save(HttpServletRequest request, HttpServletResponse response) {
        System.out.println(testService);
        TestEntity instance = TestEntity.createInstance();
        Serializable id = testService.insert(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类TestDaoTest

package com.moy.whymoy.test.mapper;

import com.moy.whymoy.test.entity.TestEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Arrays;

/**
 * [Project]:whymoy  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/7  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
public class TestDaoTest {

    @Autowired
    TestDao testDao;

    @Test
    public void insert() {
        TestEntity instance = TestEntity.createInstance();
        testDao.insert(instance);
    }

    @Test
    public void delete() {
        TestEntity instance = TestEntity.createInstance();
        testDao.insert(instance);
        testDao.delete(instance);
    }

    @Test
    public void update() {
        TestEntity instance = TestEntity.createInstance();
        testDao.insert(instance);
        instance.setDesc("我是被修改的");
        testDao.update(instance);
    }

    @Test
    public void select() {
        TestEntity instance = TestEntity.createInstance();
        testDao.insert(instance);
        System.out.println(Arrays.toString(testDao.select(instance).toArray()));
    }

    @Test
    public void count() {
        System.out.println(testDao.count(null));
    }
}
View Code

     2、测试service类TestServiceImplTest

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

import com.moy.whymoy.test.entity.TestEntity;
import com.moy.whymoy.test.service.TestService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Arrays;

/**
 * [Project]:whymoy  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/7  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
public class TestServiceImplTest {

    @Autowired
    TestService testService;

    @Test
    public void insert() {
        TestEntity instance = TestEntity.createInstance();
        testService.insert(instance);
    }

    @Test
    public void delete() {
        TestEntity instance = TestEntity.createInstance();
        testService.insert(instance);
        testService.delete(instance);
    }

    @Test
    public void update() {
        TestEntity instance = TestEntity.createInstance();
        testService.insert(instance);
        instance.setDesc("我是被修改的");
        testService.update(instance);
    }

    @Test
    public void select() {
        TestEntity instance = TestEntity.createInstance();
        testService.insert(instance);
        System.out.println(Arrays.toString(testService.select(instance).toArray()));
    }

    @Test
    public void count() {
        System.out.println(testService.count(null));
    }

}
View Code

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

 

yexiangyang

moyyexy@gmail.com


 

 

posted @ 2018-03-07 17:45  墨阳  阅读(3622)  评论(0编辑  收藏  举报