SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例


  1. 要搭建的项目的项目结构如下(使用的框架为:SpringSpingMVCMyBatis):

SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例_第1张图片

SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例_第2张图片

2.pom.xml中的配置如下(注意,本工程分为几个小的子工程,另外两个工程最终是jar包):

SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例_第3张图片

其中pom.xml中的内容如下,其中${ip}ip地址:

         4.0.0

         xxx.xxx.xxx

         xxx

         pom

         1.0-SNAPSHOT

         App tpl

 

        

                   xxx-api

                   xxx-impl

             xxx-webapp

 

 

        

                   scm:svn:http://${ip}/svn/xxx/trunk

                   scm:svn:http://${ip}/svn/xxx/trunk

                   http://${ip}/svn/xxx/trunk

        

其中xxx-xxx-webapp中的pom配置如下:

其中maven项目的目录结构:

xxx-xxx-webapp

  --src

      --main

          ---java

          ---resources

          ---webapp

      --test

  --pom.xml

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

         4.0.0

         xxx.xxx.xxx

         xxx-xxx-webapp

         war

         1.0-SNAPSHOT

         xxx-xxx-webapp

         http://maven.apache.org

        

                  

                           

                                     maven-compiler-plugin

                                     2.0.2

                                    

                                               1.5

                                               1.5

                                               true

                                               128m

                                               512m

                                               UTF-8

                                    

                           

                           

                                     maven-eclipse-plugin

                                     2.5.1

                                    

                                              

                                                       

                                                                 org.springframework.ide.eclipse.core.springnature

                                                       

                                              

                                              

                                                       

                                                                 org.springframework.ide.eclipse.core.springbuilder

                                                       

                                              

                                               false

                                               false

                                               1.5

                                    

                           

                           

                           

                                     maven-war-plugin

                                     2.1.1

                           

                  

        

        

                   UTF-8

                   4.0.3.RELEASE

        

        

                  

                  

                            org.springframework

                            spring-core

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-beans

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-orm

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-tx

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-test

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-aspects

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-webmvc

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-jms

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-context

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-context-support

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-oxm

                            ${spring.version}

                  

                  

                            org.slf4j

                            slf4j-api

                            1.7.2

                  

                  

                            log4j

                            log4j

                            1.2.17

                  

                  

                            org.slf4j

                            slf4j-log4j12

                            1.7.2

                  

 

                  

                  

                            junit

                            junit

                            4.7

                            test

                  

                  

                            aopalliance

                            aopalliance

                            1.0

                  

                  

                            commons-dbcp

                            commons-dbcp

                            1.3

                  

                  

                            commons-fileupload

                            commons-fileupload

                            1.3

                  

                  

                            commons-io

                            commons-io

                            1.4

                  

                  

                            commons-logging

                            commons-logging

                            1.1.3

                  

                  

                            commons-pool

                            commons-pool

                            1.5.4

                  

                  

                            javax.servlet

                            jstl

                            1.1.2

                  

                  

                            com.oracle

                            ojdbc14

                            10.2.0.3.0

                  

                  

                  

                            taglibs

                            standard

                            1.1.2

                  

                  

                            commons-codec

                            commons-codec

                            1.6

                  

                  

                            commons-lang

                            commons-lang

                            2.1

                  

                  

                            net.sf.ezmorph

                            ezmorph

                            1.0.6

                  

                  

                            commons-httpclient

                            commons-httpclient

                            3.1

                  

 

                  

                            net.sf.json-lib

                            json-lib

                            2.3

                            jdk15

                  

                  

                            org.apache.poi

                            poi

                            3.7

                  

                  

                  

                            org.jasig.cas.client

                            cas-client-core

                            3.2.0

                  

                  

                            org.jasig.cas.client

                            ucap-cas-client

                            3.2.1

                  

                  

                            org.mybatis

                            mybatis

                            3.2.8

                  

                  

                            org.mybatis

                            mybatis-spring

                            1.2.2

                  

                  

                            org.springframework

                            transaction

                            3.1.1

                  

                  

                            org.springframework

                            web.servlet

                            3.1.1

                  

                  

                            javax.servlet

                            servlet-api

                            2.5

                            provided

                  

                  

                            javax.servlet

                            jsp-api

                            2.0

                            provided

                  

                  

                  

                            org.json

                            org.json

                            chargebee-1.0

                  

 

                  

                  

                            net.sf.json-lib

                            json-lib

                            2.4

                            jdk15

                  

                  

                            org.codehaus.jackson

                            jackson-core-lgpl

                            1.9.13

                  

                  

                            org.codehaus.jackson

                            jackson-mapper-lgpl

                            1.9.13

                  

                  

                            org.json

                            json

                            20140107

                  

                  

                            com.ucap.webservice

                            uservices-api

                            1.0-SNAPSHOT

                  

                  

                            org.mybatis.caches

                            mybatis-ehcache

                            1.0.2

                  

                  

                  

                       mysql

                       mysql-connector-java

                       5.1.38

                  


                   

   com.alibaba
   druid
   1.0.7



       
   org.springframework.data
   spring-data-redis
   1.6.0.RELEASE


   redis.clients
   jedis
   2.7.3

        

 

其中xxx-api工程的pom文件如下:

工程结构:

SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例_第4张图片

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  4.0.0

  

                   和第一个pom文件中的pom.xml相同-->

xxx.xxx.xxx

                   和第一个pom文件中的pom.xml相同à

xxx

                   1.0-SNAPSHOT

 

  xxx.xxx.xxx

  xxx-xxx-api

  jar

  App tpl Api

  1.0-SNAPSHOT

 

                  

           

                                     maven-compiler-plugin

                                     2.0.2

                                    

                                               1.5

                                               1.5

                                               true

                                               128m

                                               512m

                                               UTF-8

                                    

                           

                           

                maven-eclipse-plugin

                2.5.1

               

                   

                        org.springframework.ide.eclipse.core.springnature

                   

                   

                        org.springframework.ide.eclipse.core.springbuilder

                   

                    false

                    false

                    1.5

               

           

                  

        

        

                   UTF-8

        

 

       这里放置的是工程中的jar依赖-->

 

其中xxx-xxx.impl工程中的pom文件如下:

工程结构如下:

SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例_第5张图片

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  4.0.0

  

                   xxx.xxx.xxx

                   xxx

                   1.0-SNAPSHOT

 

  xxx.xxx.xxx

  xxx-xxx-xxx

  jar

  App tpl Api

  1.0-SNAPSHOT

 

                  

           

                                     maven-compiler-plugin

                                     2.0.2

                                    

                                               1.5

                                               1.5

                                               true

                                               128m

                                               512m

                                               UTF-8

                                    

                           

                           

                maven-eclipse-plugin

                2.5.1

               

                   

                        org.springframework.ide.eclipse.core.springnature

                   

                   

                        org.springframework.ide.eclipse.core.springbuilder

                   

                    false

                    false

                    1.5

               

           

           

                           

                                maven-war-plugin

                                2.1.1

                           

                  

        

        

                   UTF-8

                   4.0.3.RELEASE

        

 

       

                  

                            org.springframework

                            spring-core

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-beans

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-orm

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-tx

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-test

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-aspects

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-webmvc

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-jms

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-context

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-context-support

                            ${spring.version}

                  

                  

                            org.springframework

                            spring-oxm

                            ${spring.version}

                  

                  

                            org.slf4j

                            slf4j-api

                            1.7.2

                  

                  

                            log4j

                            log4j

                            1.2.17

                  

                  

                            org.slf4j

                            slf4j-log4j12

                            1.7.2

                  

                  

       

       

               

                            junit

                            junit

                            4.7

                            test

                  

                  

                            aopalliance

                            aopalliance

                            1.0

                  

                  

                            commons-dbcp

                            commons-dbcp

                            1.3

                  

                  

                            commons-fileupload

                            commons-fileupload

                            1.3

                  

                  

                            commons-io

                            commons-io

                            1.4

                  

                  

                            commons-logging

                            commons-logging

                            1.1.3

                  

                  

                            commons-pool

                            commons-pool

                            1.5.4

                  

                  

                            javax.servlet

                            jstl

                            1.1.2

                  

                  

                            com.oracle

                            ojdbc14

                            10.2.0.3.0

                  

                  

                            taglibs

                            standard

                            1.1.2

                  

                  

                            commons-codec

                            commons-codec

                            1.6

                  

                  

                            commons-lang

                            commons-lang

                            2.1

                  

                  

                            net.sf.ezmorph

                            ezmorph

                            1.0.6

                  

                  

                            commons-httpclient

                            commons-httpclient

                            3.1

                  

                  

                            org.apache.httpcomponents

                            httpclient

                            4.3.1

                  

                  

                org.apache

                         httpmime

                         4.3

               

                  

                            net.sf.json-lib

                            json-lib

                            2.3

                            jdk15

                  

                  

                            org.apache.poi

                            poi

                            3.7

                  

                  

                            com.ucap.utils

                            utils

                            1.4-SNAPSHOT

                  

                  

                            com.ucap.base

                            base

                            1.6-SNAPSHOT

                  

                  

                            com.ucap.wcm

                            website-api

                            1.6-SNAPSHOT

                  

                  

                            xxx.xxx.xxx

                            app-tpl-api

                            1.0-SNAPSHOT

                  

                  

                            org.jasig.cas.client

                            cas-client-core

                            3.2.0

                  

                  

                            org.jasig.cas.client

                            ucap-cas-client

                            3.2.1

                  

                  

                            org.mybatis

                            mybatis

                            3.2.8

                  

                  

                            org.mybatis

                            mybatis-spring

                            1.2.2

                  

                  

                            org.springframework

                            transaction

                            3.1.1

                  

                  

                            org.springframework

                            web.servlet

                            3.1.1

                  

                  

                            javax.servlet

                            servlet-api

                            2.5

                  

                  

                com.ucap.rpc

                         rpc

                         1.1-SNAPSHOT

               

  

3.web.xml中配置使用的Spring配置的文件,代码如下:


xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
spring_Modle

contextConfigLocation
classpath:applicationContext.xml


log4jConfigLocation
classpath:log4j.properties


 
        characterEncodingFilter  
        org.springframework.web.filter.CharacterEncodingFilter  
         
            encoding  
            UTF-8  
       
 
         
            forceEncoding  
            true  
       
 
   
 
     
        characterEncodingFilter  
        /*  
   
 
    

org.springframework.web.context.request.RequestContextListener


org.springframework.web.context.ContextLoaderListener



spring
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath:context-dispatcher.xml



spring
*.action




   DruidStatView
   com.alibaba.druid.support.http.StatViewServlet


   DruidStatView
   /druid/*



   
525600



index.html
index.htm
index.jsp
default.html
default.htm
default.jsp

4、接着配置springapplicationContext.xml,配置如下:

依赖的文件是:jdbc.propertiesmybatis.xmlcontext-dispatcher.xml

jdbc.properties的配置如下:

##配置数据库类型,参数可以填写成mysqloracle,默认是oracle的数据库

dbType=oracle

#如果是mysql的配置成

#dbType=mysql

 

##Oracle对应的数据库相关配置

oracleDriver=oracle.jdbc.driver.OracleDriver

oracleUrl=jdbc:oracle:thin:@localhost:1521:orcl

oracleUsername=cmspro

oraclePassword=cmspro

 

##针对MySQL版本的时候进行如下配置

mysqlDriver=com.mysql.jdbc.Driver

mysqlUrl=jdbc\:mysql\://localhost\:3306/test

mysqlUsername=root

mysqlPassword=

mybatis.xml的配置如下:

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>

     

      <setting name="lazyLoadingEnabled" value="true" />

     

      <setting name="aggressiveLazyLoading" value="false" />

     

      <setting name="cacheEnabled" value="true" />

   settings>

 

   <typeAliases>

      <typeAlias type="xxx.xxx.xxx.entity.Component" alias="component" />

      <typeAlias type="xxx.xxx.xxx.entity.Layout" alias="layout" />

      <typeAlias type="xxx.xxx.xxx.entity.Master" alias="master" />

      <typeAlias type="xxx.xxx.xxx.entity.MasterType" alias="masterType" />

      <typeAlias type="xxx.xxx.xxx.entity.Special" alias="special" />

      <typeAlias type="xxx.xxx.xxx.entity.SpecialShare" alias="specialShare" />

      <typeAlias type="xxx.xxx.xxx.entity.SpecialVersion" alias="specialVersion" />

      <typeAlias type="xxx.xxx.xxx.entity.Style" alias="style" />

      <typeAlias type="xxx.xxx.xxx.entity.Block" alias="block" />

      <typeAlias type="xxx.xxx.xxx.entity.InnerStyle" alias="innerStyle" />

      <typeAlias type="xxx.xxx.xxx.entity.RoleFunction" alias="roleFunction" />

      <typeAlias type="xxx.xxx.xxx.entity.SpecialSharedInfo" alias="specialSharedInfo" />

   typeAliases>

 

   <plugins>

      <plugin interceptor="xxx.xxx.xxx.interceptor.PageInterceptor">plugin>

   plugins>

 

  

  

configuration>

context-dispatcher.xml的配置如下:

xml version="1.0" encoding="UTF-8"?>

<beans default-lazy-init="true"

   xmlns="http://www.springframework.org/schema/beans"

   xmlns:tx="http://www.springframework.org/schema/tx"

   xmlns:p="http://www.springframework.org/schema/p"

   xmlns:aop="http://www.springframework.org/schema/aop"

   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-3.1.xsd 

       http://www.springframework.org/schema/mvc  

       http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  

       http://www.springframework.org/schema/context 

       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 

  

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

  

   <mvc:annotation-driven>

      <mvc:message-converters>

         <bean class="org.springframework.http.converter.StringHttpMessageConverter">

            <constructor-arg value="UTF-8" />

         bean>

      mvc:message-converters>

   mvc:annotation-driven>

  

   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />

      <property name="prefix" value="/WEB-INF/pages/" />

      <property name="suffix" value=".jsp">property>

   bean>

  

   <bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>

  

   <bean id="multipartResolver"

      class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

     

  

  

  

   <mvc:interceptors>

      <bean class="xxx.xxx.xxx.interceptor.LoginInterceptor">

         <property name="redirectUrl" value="http://127.0.0.1:8888/cas/logout?service=http://127.0.0.1:8888/website-webapp/" />

      bean>

   mvc:interceptors>

 

  

  

  

   <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926" />

   <mvc:resources mapping="/img/**" location="/img/" cache-period="31556926" />

   <mvc:resources mapping="/scripts/**" location="/scripts/" cache-period="31556926" />

   <mvc:resources mapping="/styles/**" location="/styles/" cache-period="31556926" />

beans>

applicationContext.xml的配置如下:


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: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-3.1.xsd  
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
    http://www.springframework.org/schema/cache 
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd 
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task-3.1.xsd
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    
   

















   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   



















        class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
   
















class="org.springframework.jdbc.datasource.DataSourceTransactionManager">



   proxy-target-class="true"/>








   
   classpath:sqlmaps/${dbType}/*.xml





5、基于以上applicationContext.xml,我们知道,若想兼容不同的数据库、需要以下类:

SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例_第6张图片

注意:上图的sqlmaps下的目录名称和jdbc.properties中的数据库名称相同

其中:DataSourceInstances.java的代码如下:

package xxx.xxx.xxx.mapper.base.impl;

 

/**

 * DataSourceInstances.java

 * @attention 定义数据源,和applicationContext.xml中的DataSourcestargetDataSourceskey对应

 * @author toto

 * @date 2016-9-11

 * @note begin modify by 涂作权 2016-9-11 原始创建

 */

public class DataSourceInstances {

   public static final String MYSQL = "MYSQL";

   public static final String ORACLE = "ORACLE";

}

 

DataSourceSwitch.java的代码如下:

package xxx.xxx.xxx.mapper.base.impl;

 

/**

 * DataSourceSwitch.java 用于切换数据库类型

 * @attention

 * @author toto

 * @date 2016-9-11

 * @note begin modify by 涂作权 2016-9-11 原始创建

 */

@SuppressWarnings({"unchecked"})

public class DataSourceSwitch {

   private static final ThreadLocal contextHolder = new ThreadLocal();

  

   public static void setDataSourceType(String dataSourceType) {

      contextHolder.set(dataSourceType);

   }

  

   public static String getDataSourceType() {

      return (String)contextHolder.get();

   }

  

   public static void clearDataSourceType() {

      contextHolder.remove();

   }

}

DataSources.java的代码结构如下:

package xxx.xxx.xxx.mapper.base.impl;

 

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

 

/**

 * DataSources.java 类或者接口的简要说明

 * @attention

配置于applicationContext,线程局部变量ThreadLocal contextHolder保存当前需要的数据类型

 *

DataSourceSwitch.setDataSourceType(DataSourceInstances.xxxx),保存当前需要的数据源类型的,

 *

DataSources会从当前线程中查找线程变量的数据类型,从而决定使用何种类型的数据员

 *

 * @author toto

 * @date 2016-9-11

 * @note begin modify by 涂作权 2016-9-11 原始创建

 */

public class DataSources extends AbstractRoutingDataSource {

   //private static final Logger logger = Logger.getLogger(DataSources.class);

   public String dbType;

  

   //@Override

   protected Object determineCurrentLookupKey() {

      if (dbType.equalsIgnoreCase(DataSourceInstances.MYSQL)) {

         DataSourceSwitch.setDataSourceType(DataSourceInstances.MYSQL);

      } else if(dbType.equalsIgnoreCase(DataSourceInstances.ORACLE)) {

         DataSourceSwitch.setDataSourceType(DataSourceInstances.ORACLE);

      } else {

         DataSourceSwitch.setDataSourceType(DataSourceInstances.ORACLE);

      }

      return DataSourceSwitch.getDataSourceType();

   }

 

   public String getDbType() {

      return dbType;

   }

 

   public void setDbType(String dbType) {

      this.dbType = dbType;

   }

}

6、其它常用工具:

公共的mapper

package xxx.xxx.xxx.mapper.base.impl;

 

import java.io.Serializable;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import javax.annotation.Resource;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.log4j.Logger;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;

 

import xxx.xxx.xxx.mapper.base.BaseMapper;

import com.ucap.utils.UUIDGenerator;

 

@SuppressWarnings("unchecked")

public class BaseMapperImpl extends

                   SqlSessionDaoSupport implements BaseMapper {

 

         public static Logger logger = Logger.getLogger(BaseMapperImpl.class);

 

         private Class entityClass = null;

 

         /**

          * 创建默认构造方法,以取得真正的泛型类型

          */

         public BaseMapperImpl() {

                   Class c = getClass();

                   Type type = c.getGenericSuperclass();

 

                   if (type instanceof ParameterizedType) {

                            Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();

                            entityClass = (Class) parameterizedType[0];

                   }

         }

 

         @Resource(name = "sqlSessionFactory")

         public void setSuperSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {

                   super.setSqlSessionFactory(sqlSessionFactory);

         }

 

         // 保存实体对象

         @CacheEvict(value = "ehcache", allEntries = true)

         public T insert(T entity) {

        try {

                 Field[] fileds = entity.getClass().getDeclaredFields();

                            for (Field field : fileds) {

                                     if (field.getName().equals("id")) {

                                               Method setIdMethod = entity.getClass().getDeclaredMethod(

                                                                 "setId", String.class);

                                               setIdMethod.invoke(entity, UUIDGenerator.generate());

                                     }

                            }

                   } catch (Exception e) {

                            e.printStackTrace();

                   }

                  

                   getSqlSession().insert(entity.getClass().getName() + "Mapper.insert",entity);

 

                   return entity;

         }

 

         // 更新

         @CacheEvict(value = "ehcache", allEntries = true)

         public void update(T entity) {

                   getSqlSession().update(entity.getClass().getName() + "Mapper.update",entity);

         }

 

         // 根据id删除某个对象

         @CacheEvict(value = "ehcache", allEntries = true)

         public void deleteById(PK id) {

                   getSqlSession().delete(entityClass.getName() + "Mapper.deleteById", id);

         }

        

         //根据id,逻辑上删除某个对象(更行状态值)

         public void deleteByUpdateState(PK id) {

                   getSqlSession().delete(entityClass.getName() + "Mapper.deleteByUpdateState", id);

         }

 

         // 根据id加载某个对象

         @Cacheable(value = "ehcache", key = "#id")

         public T fetch(PK id) {

                   return (T)getSqlSession().selectOne(entityClass.getName() + "Mapper.fetch", id);

         }

 

         // 查找所有的对象

         public List findAll() {

                   return (List)getSqlSession().selectList(entityClass.getName() + "Mapper.findAll", null);

         }

        

         //设置是否共享,如果SHARESTATE = 1 表示的是共享,SHARESTATE = 0:表示专享

         public void updateShareState(T entity) {

                   getSqlSession().update(entityClass.getName() + "Mapper.updateShareState", entity);

         }

 

         /**

          * 查询所有对象:分页查询 

          * @param paramMap

          * @return 返回某1页的数据

          * @attention 方法的使用注意事项  【必带参数:page

          * @author YangWeiQiang

          * @date 2015-11-12

          */

         public List findAllByPage(Map paramMap) {

                   return (List)getSqlSession().selectList(entityClass.getName() + "Mapper.queryListByPage", paramMap);

         }

        

         // 根据查询参数,当前页数,每页显示的数目得到分页列表

         /*

         @Cacheable(value = "ehcache", key = "'queryPage-'+#condition+'-'+#currentPage+'-'+#pageSize")

         public Pager queryPage(Map condition,

                            Integer currentPage, Integer pageSize) {

 

                   Pager pager = new Pager(pageSize, count(condition), currentPage);

 

                   try {

 

                            if (condition == null) {

 

                                     condition = new HashMap();

 

                            }

 

                            condition.put("beginRow", (pager.getCurrentPage() - 1)

                                               * pager.getPageSize());

 

                            condition.put("pageSize", pager.getPageSize());

 

                            List dataList = this.getSqlSession().selectList(

                                               entityClass.getName() + "Mapper.queryList", condition);

 

                            pager.setDataList(dataList);

 

                            return pager;

 

                   } catch (RuntimeException re) {

                            logger.error("findList " + entityClass.getName() + "failed :{}",

                                                                 re);

                            re.printStackTrace();

                   }

 

                   return null;

 

         }*/

 

         /**

          * 通过条件查询

          */

         public int count(Map condition) {

                   int count = (Integer)getSqlSession().selectOne(entityClass.getName() + "Mapper.count", condition);

                   return count;

         }

 

         @Cacheable(value = "ehcache", key = "'queryList-'+#condition+'-orderBy-'+#orderBy+'-sortBy-'+#sortBy")

         public List queryList(Map condition, String orderBy,

                            String sortBy) {

 

                   if (condition == null) {

                            condition = new HashMap();

                            condition.put("orderBy", orderBy);

                            condition.put("sortBy", sortBy);

                   }

 

                   return (List)getSqlSession().selectList(

                                     entityClass.getName() + "Mapper.queryList", condition);

         }

 

         /**

          * 通过条件查询一条

          */

         @Cacheable(value = "ehcache", key = "'queryOne-'+#condition")

         public T queryOne(Map condition) {

                   return (T)getSqlSession().selectOne(

                                     entityClass.getName() + "Mapper.queryOne", condition);

         }

        

         /**

          * 更新或保存

          */

         @CacheEvict(value = "ehcache", allEntries = true)

         public T updateOrSave(T t, PK id) {

                   if (null != fetch(id)) {

                            update(t);

                   } else {

                            return insert(t);

                   }

                   return t;

         }

        

         @Cacheable(value = "ehcache", key = "'findOne-'+#property+'-'+#value")

         public T findOne(String property, Object value) {

                   Map condition = new HashMap();

                   condition.put(property, value);

                   return (T)getSqlSession().selectOne(

                                     entityClass.getName() + "Mapper.findOne", condition);

         }

 

         @Cacheable(value = "ehcache", key = "'findList-'+#property+'-'+#value")

         public List findList(String property, Object value) {

                   Map condition = new HashMap();

                   condition.put(property, value);

                   return getSqlSession().selectList(

                                     entityClass.getName() + "Mapper.findList", condition);

         }

 

         public Class getEntityClass() {

                   return entityClass;

         }

        

         public Integer selectMaxId() {

                   return getSqlSession().selectOne(

                                     entityClass.getName() + "Mapper.selectMaxId");

         }

 

         @CacheEvict(value = "ehcache", allEntries = true)

         public void deleteByCondition(Map condition) {

 

                   getSqlSession().delete(

                                     entityClass.getName() + "Mapper.deleteByCondition", condition);

 

         }

 

         @CacheEvict(value = "ehcache", allEntries = true)

         public void deleteByProperty(String property, Object value) {

                   Map condition = new HashMap();

                   condition.put(property, value);

                   deleteByCondition(condition);

         }

 

         @CacheEvict(value = "ehcache", allEntries = true)

         public void updateNull(T entity) {

                   getSqlSession().update(entityClass.getName() + "Mapper.updateNull",entity);

         }

 

         @Cacheable(value = "ehcache", key = "'selectOne-'+#mapperId+'-'+#obj")

         public T selectOne(String mapperId, Object obj) {

                   return (T)getSqlSession().selectOne(

                                     entityClass.getName() + "Mapper." + mapperId, obj);

         }

 

         @Cacheable(value = "ehcache", key = "'selectList-'+#mapperId+'-'+#obj")

         public List selectList(String mapperId, Object obj) {

                   return getSqlSession().selectList(

                                     entityClass.getName() + "Mapper." + mapperId, obj);

         }

 

         @CacheEvict(value = "ehcache", allEntries = true)

         public List insertList(List entities) {

                  return getSqlSession().selectList(

                                     entityClass.getName() + "Mapper.insertList", entities);

         }

 

         /*

         public DetailsPager queryDetailsPage(Map condition, PK id) {

 

                   T currentObj = fetch(id);

 

                   if (currentObj != null) {

 

                            List ids = getSqlSession().selectList(

                                               entityClass.getName() + "Mapper.findIds", condition);

 

                            int currentObjIndex = ids.indexOf(id);

 

                            DetailsPager page = new DetailsPager(currentObj);

 

                            if (currentObjIndex > 0)

 

                                     page.setPreObj(fetch(ids.get(currentObjIndex - 1)));

 

                            if (currentObjIndex < ids.size() - 1)

 

                                     page.setNextObj(fetch(ids.get(currentObjIndex + 1)));

 

                            return page;

 

                   }

 

                   return null;

         }*/

        

         public List like(String property, Object value) {

                   Map condition = new HashMap();

                   condition.put(property, value);

                   return getSqlSession().selectList(

                                     entityClass.getName() + "Mapper.like", condition);

         }

}

xxx-xxx-webapp中的单元测试写法:

package xxx.xxx.xxx;

 

import javax.annotation.Resource;

 

import org.apache.log4j.Logger;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 

import xxx.xxx.xxx.entity.Component;

import xxx.xxx.xxx.service.component.ComponentService;

 

/**

 * ComponentTestCase.java 单元测试案例

 * @attention

 * @author toto

 * @date 2016-8-24

 * @note begin modify by 涂作权 2016-8-24 原始创建

 */

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = {

                   "classpath:context-dispatcher.xml",

                   "classpath:applicationContext.xml"})

public class ComponentTestCase {

         private static final Logger logger = Logger.getLogger(ComponentTestCase.class);

        

         @Resource(name = "componentService")

         private ComponentService componentService;

        

         @Test

         public void testHello() {

                   Component component = componentService.findComponent("98a77fe0a737400b80c354b216773119");

                   logger.info("-----------------------");

                   logger.info(component.getComponentName());

                   logger.info("-----------------------");

         }

}

httpClient调用http请求。其中接口是一个action,直接返回的是json数据。

         String url = ExtendedServerConfig.getInstance().getStringProperty("MANUSCRIPTS_APPENDIXS_URL");

         String result = "";

         HttpPost httpRequest = new HttpPost(url);

        

         List nameValuePairs = new ArrayList();

         nameValuePairs.add(new BasicNameValuePair("params", params));

        

         httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));

         HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

         //释放post请求

         //httpRequest.abort();

        

         if (httpResponse.getStatusLine().getStatusCode() == 200) {

            HttpEntity httpEntity = httpResponse.getEntity();

            result = EntityUtils.toString(httpEntity);

         }

 maven常用命令:

mvn -Pall eclipse:eclipse

mvn clean

mvn compile -Dmaven.test.skip=true
mvn install -Dmaven.test.skip=true
mvn package -Dmaven.test.skip=true

你可能感兴趣的:(#,Spring,#,#,Spring,MVC,#,maven/ant打包,#,httpClient,#,c3p0/Druid连接池)