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

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 要搭建的项目的项目结构如下(使用的框架为:Spring、SpingMVC、MyBatis):2.pom.xml中的配置如下(注意,本工程分为几个小的子工程,另外两个工程最终是jar包):其中pom.xml中的内容如下,其中${ip}为ip地址: <?xml version="1.0" encoding="UTF-8"?> <project

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

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

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

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

<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>xxx.xxx.xxx</groupId>

         <artifactId>xxx</artifactId>

         <packaging>pom</packaging>

         <version>1.0-SNAPSHOT</version>

         <name>App tpl</name>

 

         <modules>

                   <module>xxx-api</module>

                   <module>xxx-impl</module>

             <module>xxx-webapp</module>

  </modules>

 

         <scm>

                   <connection>scm:svn:http://${ip}/svn/xxx/trunk</connection>

                   <developerConnection>scm:svn:http://${ip}/svn/xxx/trunk</developerConnection>

                   <url>http://${ip}/svn/xxx/trunk</url>

         </scm>

</project>

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

其中maven项目的目录结构:

xxx-xxx-webapp

  --src

      --main

          ---java

          ---resources

          ---webapp

      --test

  --pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

         <modelVersion>4.0.0</modelVersion>

         <groupId>xxx.xxx.xxx</groupId>

         <artifactId>xxx-xxx-webapp</artifactId>

         <packaging>war</packaging>

         <version>1.0-SNAPSHOT</version>

         <name>xxx-xxx-webapp</name>

         <url>http://maven.apache.org</url>

         <build>

                   <plugins>

                            <plugin>

                                     <artifactId>maven-compiler-plugin</artifactId>

                                     <version>2.0.2</version>

                                     <configuration>

                                               <source>1.5</source>

                                               <target>1.5</target>

                                               <fork>true</fork>

                                               <meminitial>128m</meminitial>

                                               <maxmem>512m</maxmem>

                                               <encoding>UTF-8</encoding>

                                     </configuration>

                            </plugin>

                            <plugin>

                                     <artifactId>maven-eclipse-plugin</artifactId>

                                     <version>2.5.1</version>

                                     <configuration>

                                               <additionalProjectnatures>

                                                        <projectnature>

                                                                 org.springframework.ide.eclipse.core.springnature

                                                        </projectnature>

                                               </additionalProjectnatures>

                                               <additionalBuildcommands>

                                                        <buildcommand>

                                                                 org.springframework.ide.eclipse.core.springbuilder

                                                        </buildcommand>

                                               </additionalBuildcommands>

                                               <downloadSources>false</downloadSources>

                                               <downloadJavadocs>false</downloadJavadocs>

                                               <wtpversion>1.5</wtpversion>

                                     </configuration>

                            </plugin>

                            <!-- 要加上下面的一句,否则执行:mvn package -Dmaven.test.skip=true的时候会报错 -->

                            <plugin>

                                     <artifactId>maven-war-plugin</artifactId>

                                     <version>2.1.1</version>

                            </plugin>

                   </plugins>

         </build>

         <properties>

                   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

                   <spring.version>4.0.3.RELEASE</spring.version>

         </properties>

         <dependencies>

                   <!-- Spring -->

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-core</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-beans</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-orm</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-tx</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-test</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-aspects</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-webmvc</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-jms</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-context</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-context-support</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-oxm</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.slf4j</groupId>

                            <artifactId>slf4j-api</artifactId>

                            <version>1.7.2</version>

                   </dependency>

                   <dependency>

                            <groupId>log4j</groupId>

                            <artifactId>log4j</artifactId>

                            <version>1.2.17</version>

                   </dependency>

                   <dependency>

                            <groupId>org.slf4j</groupId>

                            <artifactId>slf4j-log4j12</artifactId>

                            <version>1.7.2</version>

                   </dependency>

 

                   <!-- Test -->

                   <dependency>

                            <groupId>junit</groupId>

                            <artifactId>junit</artifactId>

                            <version>4.7</version>

                            <scope>test</scope>

                   </dependency>

                   <dependency>

                            <groupId>aopalliance</groupId>

                            <artifactId>aopalliance</artifactId>

                            <version>1.0</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-dbcp</groupId>

                            <artifactId>commons-dbcp</artifactId>

                            <version>1.3</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-fileupload</groupId>

                            <artifactId>commons-fileupload</artifactId>

                            <version>1.3</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-io</groupId>

                            <artifactId>commons-io</artifactId>

                            <version>1.4</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-logging</groupId>

                            <artifactId>commons-logging</artifactId>

                            <version>1.1.3</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-pool</groupId>

                            <artifactId>commons-pool</artifactId>

                            <version>1.5.4</version>

                   </dependency>

                   <dependency>

                            <groupId>javax.servlet</groupId>

                            <artifactId>jstl</artifactId>

                            <version>1.1.2</version>

                   </dependency>

                   <dependency>

                            <groupId>com.oracle</groupId>

                            <artifactId>ojdbc14</artifactId>

                            <version>10.2.0.3.0</version>

                   </dependency>

                  

                   <dependency>

                            <groupId>taglibs</groupId>

                            <artifactId>standard</artifactId>

                            <version>1.1.2</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-codec</groupId>

                            <artifactId>commons-codec</artifactId>

                            <version>1.6</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-lang</groupId>

                            <artifactId>commons-lang</artifactId>

                            <version>2.1</version>

                   </dependency>

                   <dependency>

                            <groupId>net.sf.ezmorph</groupId>

                            <artifactId>ezmorph</artifactId>

                            <version>1.0.6</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-httpclient</groupId>

                            <artifactId>commons-httpclient</artifactId>

                            <version>3.1</version>

                   </dependency>

 

                   <dependency>

                            <groupId>net.sf.json-lib</groupId>

                            <artifactId>json-lib</artifactId>

                            <version>2.3</version>

                            <classifier>jdk15</classifier>

                   </dependency>

                   <dependency>

                            <groupId>org.apache.poi</groupId>

                            <artifactId>poi</artifactId>

                            <version>3.7</version>

                   </dependency>

                  

                   <dependency>

                            <groupId>org.jasig.cas.client</groupId>

                            <artifactId>cas-client-core</artifactId>

                            <version>3.2.0</version>

                   </dependency>

                   <dependency>

                            <groupId>org.jasig.cas.client</groupId>

                            <artifactId>ucap-cas-client</artifactId>

                            <version>3.2.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.mybatis</groupId>

                            <artifactId>mybatis</artifactId>

                            <version>3.2.8</version>

                   </dependency>

                   <dependency>

                            <groupId>org.mybatis</groupId>

                            <artifactId>mybatis-spring</artifactId>

                            <version>1.2.2</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>transaction</artifactId>

                            <version>3.1.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>web.servlet</artifactId>

                            <version>3.1.1</version>

                   </dependency>

                   <dependency>

                            <groupId>javax.servlet</groupId>

                            <artifactId>servlet-api</artifactId>

                            <version>2.5</version>

                            <scope>provided</scope>

                   </dependency>

                   <dependency>

                            <groupId>javax.servlet</groupId>

                            <artifactId>jsp-api</artifactId>

                            <version>2.0</version>

                            <scope>provided</scope>

                   </dependency>

                   <!--CMS引用json -->

                   <dependency>

                            <groupId>org.json</groupId>

                            <artifactId>org.json</artifactId>

                            <version>chargebee-1.0</version>

                   </dependency>

 

                   <!-- json -->

                   <dependency>

                            <groupId>net.sf.json-lib</groupId>

                            <artifactId>json-lib</artifactId>

                            <version>2.4</version>

                            <classifier>jdk15</classifier>

                   </dependency>

                   <dependency>

                            <groupId>org.codehaus.jackson</groupId>

                            <artifactId>jackson-core-lgpl</artifactId>

                            <version>1.9.13</version>

                   </dependency>

                   <dependency>

                            <groupId>org.codehaus.jackson</groupId>

                            <artifactId>jackson-mapper-lgpl</artifactId>

                            <version>1.9.13</version>

                   </dependency>

                   <dependency>

                            <groupId>org.json</groupId>

                            <artifactId>json</artifactId>

                            <version>20140107</version>

                   </dependency>

                   <dependency>

                            <groupId>com.ucap.webservice</groupId>

                            <artifactId>uservices-api</artifactId>

                            <version>1.0-SNAPSHOT</version>

                   </dependency>

                   <dependency>

                            <groupId>org.mybatis.caches</groupId>

                            <artifactId>mybatis-ehcache</artifactId>

                            <version>1.0.2</version>

                   </dependency>

                   <!-- 提交兼容MySQL的依赖 -->

                   <dependency>

                       <groupId>mysql</groupId>

                       <artifactId>mysql-connector-java</artifactId>

                       <version>5.1.38</version>

                   </dependency>


                   <!-- 阿里巴巴的druid数据源配置 -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.7</version>
</dependency>

<!-- 整合redis所需的jar包 -->
        <dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-redis</artifactId>
   <version>1.6.0.RELEASE</version>
</dependency>
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.7.3</version>
</dependency>

         </dependencies>

</project>

 

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

工程结构:

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

   <parent>

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

<groupId>xxx.xxx.xxx</groupId>

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

<artifactId>xxx</artifactId>

                   <version>1.0-SNAPSHOT</version>

  </parent>

  <groupId>xxx.xxx.xxx</groupId>

  <artifactId>xxx-xxx-api</artifactId>

  <packaging>jar</packaging>

  <name>App tpl Api</name>

  <version>1.0-SNAPSHOT</version>

  <build>

                   <plugins>

            <plugin>

                                     <artifactId>maven-compiler-plugin</artifactId>

                                     <version>2.0.2</version>

                                     <configuration>

                                               <source>1.5</source>

                                               <target>1.5</target>

                                               <fork>true</fork>

                                               <meminitial>128m</meminitial>

                                               <maxmem>512m</maxmem>

                                               <encoding>UTF-8</encoding>

                                     </configuration>

                            </plugin>

                            <plugin>

                <artifactId>maven-eclipse-plugin</artifactId>

                <version>2.5.1</version>

                <configuration>

                    <additionalProjectnatures>

                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>

                    </additionalProjectnatures>

                    <additionalBuildcommands>

                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>

                    </additionalBuildcommands>

                    <downloadSources>false</downloadSources>

                    <downloadJavadocs>false</downloadJavadocs>

                    <wtpversion>1.5</wtpversion>

                </configuration>

            </plugin>

                   </plugins>

         </build>

         <properties>

                   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

         </properties>

  <dependencies>

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

  </dependencies>

</project>

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

工程结构如下:

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

   <parent>

                   <groupId>xxx.xxx.xxx</groupId>

                   <artifactId>xxx</artifactId>

                   <version>1.0-SNAPSHOT</version>

  </parent>

  <groupId>xxx.xxx.xxx</groupId>

  <artifactId>xxx-xxx-xxx</artifactId>

  <packaging>jar</packaging>

  <name>App tpl Api</name>

  <version>1.0-SNAPSHOT</version>

  <build>

                   <plugins>

            <plugin>

                                     <artifactId>maven-compiler-plugin</artifactId>

                                     <version>2.0.2</version>

                                     <configuration>

                                               <source>1.5</source>

                                               <target>1.5</target>

                                               <fork>true</fork>

                                               <meminitial>128m</meminitial>

                                               <maxmem>512m</maxmem>

                                               <encoding>UTF-8</encoding>

                                     </configuration>

                            </plugin>

                            <plugin>

                <artifactId>maven-eclipse-plugin</artifactId>

                <version>2.5.1</version>

                <configuration>

                    <additionalProjectnatures>

                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>

                    </additionalProjectnatures>

                    <additionalBuildcommands>

                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>

                    </additionalBuildcommands>

                    <downloadSources>false</downloadSources>

                    <downloadJavadocs>false</downloadJavadocs>

                    <wtpversion>1.5</wtpversion>

                </configuration>

            </plugin>

            <!-- 要加上下面的一句,否则执行:mvn package -Dmaven.test.skip=true的时候会报错 -->

                            <plugin>

                                <artifactId>maven-war-plugin</artifactId>

                                <version>2.1.1</version>

                            </plugin>

                   </plugins>

         </build>

         <properties>

                   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

                   <spring.version>4.0.3.RELEASE</spring.version>

         </properties>

  <dependencies>

        <!--

        Spring,使用下面的方式之后能够使用 @RunWith(SpringJUnit4ClassRunner.class)

        的方式编写单元测试了

        -->

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-core</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-beans</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-orm</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-tx</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-test</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-aspects</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-webmvc</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-jms</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-context</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-context-support</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring-oxm</artifactId>

                            <version>${spring.version}</version>

                   </dependency>

                   <dependency>

                            <groupId>org.slf4j</groupId>

                            <artifactId>slf4j-api</artifactId>

                            <version>1.7.2</version>

                   </dependency>

                   <dependency>

                            <groupId>log4j</groupId>

                            <artifactId>log4j</artifactId>

                            <version>1.2.17</version>

                   </dependency>

                   <dependency>

                            <groupId>org.slf4j</groupId>

                            <artifactId>slf4j-log4j12</artifactId>

                            <version>1.7.2</version>

                   </dependency>

                  

       

        <!-- Test -->

                <dependency>

                            <groupId>junit</groupId>

                            <artifactId>junit</artifactId>

                            <version>4.7</version>

                            <scope>test</scope>

                   </dependency>

                   <dependency>

                            <groupId>aopalliance</groupId>

                            <artifactId>aopalliance</artifactId>

                            <version>1.0</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-dbcp</groupId>

                            <artifactId>commons-dbcp</artifactId>

                            <version>1.3</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-fileupload</groupId>

                            <artifactId>commons-fileupload</artifactId>

                            <version>1.3</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-io</groupId>

                            <artifactId>commons-io</artifactId>

                            <version>1.4</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-logging</groupId>

                            <artifactId>commons-logging</artifactId>

                            <version>1.1.3</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-pool</groupId>

                            <artifactId>commons-pool</artifactId>

                            <version>1.5.4</version>

                   </dependency>

                   <dependency>

                            <groupId>javax.servlet</groupId>

                            <artifactId>jstl</artifactId>

                            <version>1.1.2</version>

                   </dependency>

                   <dependency>

                            <groupId>com.oracle</groupId>

                            <artifactId>ojdbc14</artifactId>

                            <version>10.2.0.3.0</version>

                   </dependency>

                   <dependency>

                            <groupId>taglibs</groupId>

                            <artifactId>standard</artifactId>

                            <version>1.1.2</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-codec</groupId>

                            <artifactId>commons-codec</artifactId>

                            <version>1.6</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-lang</groupId>

                            <artifactId>commons-lang</artifactId>

                            <version>2.1</version>

                   </dependency>

                   <dependency>

                            <groupId>net.sf.ezmorph</groupId>

                            <artifactId>ezmorph</artifactId>

                            <version>1.0.6</version>

                   </dependency>

                   <dependency>

                            <groupId>commons-httpclient</groupId>

                            <artifactId>commons-httpclient</artifactId>

                            <version>3.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.apache.httpcomponents</groupId>

                            <artifactId>httpclient</artifactId>

                            <version>4.3.1</version>

                   </dependency>

                   <dependency>

                <groupId>org.apache</groupId>

                         <artifactId>httpmime</artifactId>

                         <version>4.3</version>

                </dependency>

                   <dependency>

                            <groupId>net.sf.json-lib</groupId>

                            <artifactId>json-lib</artifactId>

                            <version>2.3</version>

                            <classifier>jdk15</classifier>

                   </dependency>

                   <dependency>

                            <groupId>org.apache.poi</groupId>

                            <artifactId>poi</artifactId>

                            <version>3.7</version>

                   </dependency>

                   <dependency>

                            <groupId>com.ucap.utils</groupId>

                            <artifactId>utils</artifactId>

                            <version>1.4-SNAPSHOT</version>

                   </dependency>

                   <dependency>

                            <groupId>com.ucap.base</groupId>

                            <artifactId>base</artifactId>

                            <version>1.6-SNAPSHOT</version>

                   </dependency>

                   <dependency>

                            <groupId>com.ucap.wcm</groupId>

                            <artifactId>website-api</artifactId>

                            <version>1.6-SNAPSHOT</version>

                   </dependency>

                   <dependency>

                            <groupId>xxx.xxx.xxx</groupId>

                            <artifactId>app-tpl-api</artifactId>

                            <version>1.0-SNAPSHOT</version>

                   </dependency>

                   <dependency>

                            <groupId>org.jasig.cas.client</groupId>

                            <artifactId>cas-client-core</artifactId>

                            <version>3.2.0</version>

                   </dependency>

                   <dependency>

                            <groupId>org.jasig.cas.client</groupId>

                            <artifactId>ucap-cas-client</artifactId>

                            <version>3.2.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.mybatis</groupId>

                            <artifactId>mybatis</artifactId>

                            <version>3.2.8</version>

                   </dependency>

                   <dependency>

                            <groupId>org.mybatis</groupId>

                            <artifactId>mybatis-spring</artifactId>

                            <version>1.2.2</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>transaction</artifactId>

                            <version>3.1.1</version>

                   </dependency>

                   <dependency>

                            <groupId>org.springframework</groupId>

                            <artifactId>web.servlet</artifactId>

                            <version>3.1.1</version>

                   </dependency>

                   <dependency>

                            <groupId>javax.servlet</groupId>

                            <artifactId>servlet-api</artifactId>

                            <version>2.5</version>

                   </dependency>

                   <dependency>

                <groupId>com.ucap.rpc</groupId>

                         <artifactId>rpc</artifactId>

                         <version>1.1-SNAPSHOT</version>

                </dependency>

  </dependencies>

</project>

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

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<display-name>spring_Modle</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>

<filter>  
        <filter-name>characterEncodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 
    
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:context-dispatcher.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>

<!-- druid -->
<servlet>
   <servlet-name>DruidStatView</servlet-name>
   <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>DruidStatView</servlet-name>
   <url-pattern>/druid/*</url-pattern>
</servlet-mapping>

<session-config>
   <!-- 设置过期时间为一年,相当于是一年都不过期 -->
<session-timeout>525600</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

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

      <!--积极加载设置成false -->

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

 

   <!-- 下面的Mapper文件在app-tpl-impl中定义 -->

   <!--

   <mappers>

      <mapper resource="sqlmaps/ComponentMapper.xml" />

      <mapper resource="sqlmaps/LayoutMapper.xml" />

      <mapper resource="sqlmaps/MasterMapper.xml" />

      <mapper resource="sqlmaps/MasterTypeMapper.xml" />

      <mapper resource="sqlmaps/SpecialMapper.xml" />

      <mapper resource="sqlmaps/SpecialShareMapper.xml" />

      <mapper resource="sqlmaps/SpecialVersionMapper.xml" />

      <mapper resource="sqlmaps/StyleMapper.xml" />

      <mapper resource="sqlmaps/BlockMapper.xml" />

      <mapper resource="sqlmaps/InnerStyleMapper.xml" />

      <mapper resource="sqlmaps/RoleFunctionMapper.xml" />

   </mappers>

   -->

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

   <!-- 通过注解,把URL映射到Controller上,该标签默认注册DefaultAnnotationHandlerMappingAnnotationMethodHandlerAdapter

-->

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

     

   <!--<bean id="multipartResolver" class="xxx.xxx.xxx.resolver.MyCommonsMultipartResolver">

        <property name="maxUploadSize" value="20480000"/>1024*2020k

        <property name="resolveLazily" value="true"/>resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常

        <property name="defaultEncoding" value="UTF-8"/>

   </bean>

   -->

  

   <!-- 拦截器 -->

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

 

   <!-- 总错误处理 -->

   <!--

   <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

      <property name="defaultErrorView">

         <value>/error/error</value>

      </property>

      <property name="defaultStatusCode">

         <value>500</value>

      </property>

      <property name="warnLogCategory">

         <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>

      </property>

   </bean>

   -->

   <!-- 对静态资源文件的访问  -->

   <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的配置如下:

<?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: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">
    
    <!-- 缓存配置
    <ehcache:annotation-driven cache-manager="cacheManager" />  
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:ehcache.xml"/>  
    </bean>
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="cacheManagerFactory" />
    </bean>
     -->
<!-- 打开注解 -->
<context:annotation-config />
<!-- 打开自动扫描 -->
<context:component-scan base-package="xxx.xxx.xxx" />

<!-- 定时器驱动 -->
<task:annotation-driven/>

<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties" />


<!-- 
以下用于配置多数据源
配置parentDataSource的父bean,再配置多个数据源继承这个bean,对driverClassName、
url、username、password等数据源连接参数进行各自的重写、例如mysqlDataSource、
在DataSource bean中要注入所要切换的数据、并且设置默认的数据源
-->
<!--<bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"></bean>
创建MySQL对应的jdbc数据源 
<bean id="mysqlDataSource" parent="parentDataSource">
<property name="driverClassName" value="${mysqlDriver}"></property>
<property name="url" value="${mysqlUrl}"></property>
<property name="username" value="${mysqlUsername}"></property>
<property name="password" value="${mysqlPassword}"></property>
</bean>
-->

<!-- 数据源 org.apache.commons.dbcp.BasicDataSource com.alibaba.druid.pool.DruidDataSource -->
<bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource">
   <!-- 初始化连接大小 -->
   <property name="initialSize" value="8" />
   <!-- 连接池最大使用连接数量 -->
   <property name="maxActive" value="32" />
   <!-- 连接池最小空闲 -->
   <property name="minIdle" value="4" />
   <!-- 获取连接最大等待时间 -->
   <property name="maxWait" value="60000" />
   
   <!--<property name="validationQuery"><value>SELECT 1</value></property>-->
   <property name="testOnBorrow" value="false" />
   <property name="testOnReturn" value="false" />
   <property name="testWhileIdle" value="true" />
   
   <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
   <property name="timeBetweenEvictionRunsMillis" value="60000" />
   <!-- 配置一个连接池中最小生存的时间,单位是毫秒 -->
   <property name="minEvictableIdleTimeMillis" value="25200000" />
   
   <!-- 打开removeAbandoned功能 -->
   <property name="removeAbandoned" value="true" />
   <!-- 1800秒,也就是30分钟 -->
   <property name="removeAbandonedTimeout" value="1800" />
   <!-- 关闭abanded连接时输出错误日志 -->
   <property name="logAbandoned" value="true" />
   <!-- 监控数据库 -->
   <property name="filters" value="mergeStat" />
</bean>
<!-- 创建MySQL对应的jdbc数据源 -->
<bean id="mysqlDataSource" parent="parentDataSource">
<property name="driverClassName" value="${mysqlDriver}"></property>
<property name="url" value="${mysqlUrl}"></property>
<property name="username" value="${mysqlUsername}"></property>
<property name="password" value="${mysqlPassword}"></property>
</bean>


<!--创建jdbc数据源 -->
<bean id="oracleDataSource" parent="parentDataSource">
<property name="driverClassName" value="${oracleDriver}" />
<property name="url" value="${oracleUrl}" />
<property name="username" value="${oracleUsername}" />
<property name="password" value="${oraclePassword}" />
</bean>

<!-- 配置druid监控spring jdbc -->
<bean id="druid-stat-interceptor"
        class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>

<!-- 注意下面的com.ucap.tpl.mapper.base.impl.DataSources是自己定义的数据源-->
<bean id="dataSource" class="com.ucap.tpl.mapper.base.impl.DataSources">
<property name="dbType" value="${dbType}"></property>
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 注意下面的key的值要和DataSourceInstances中定义的值相同-->
<entry value-ref="mysqlDataSource" key="MYSQL"></entry>
<entry value-ref="oracleDataSource" key="ORACLE"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="oracleDataSource"></property>
</bean>

<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"
   proxy-target-class="true"/>


<!-- 创建SqlSessionFactory,同时指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis.xml"/>
<property name="mapperLocations">
<list>
   <!-- 配置Mapper文件 -->
   <value>classpath:sqlmaps/${dbType}/*.xml</value>
</list>
</property>
</bean>

<import resource="redis-context.xml"/>
</beans>

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

注意:上图的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 <p>配置于applicationContext,线程局部变量ThreadLocal contextHolder保存当前需要的数据类型</p>

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

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

 *

 * @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<T, PK extends Serializable> extends

                   SqlSessionDaoSupport implements BaseMapper<T, PK> {

 

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

 

         private Class<T> entityClass = null;

 

         /**

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

          */

         public BaseMapperImpl() {

                   Class<?> c = getClass();

                   Type type = c.getGenericSuperclass();

 

                   if (type instanceof ParameterizedType) {

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

                            entityClass = (Class<T>) 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<T> findAll() {

                   return (List<T>)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<T> findAllByPage(Map paramMap) {

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

         }

        

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

         /*

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

         public Pager<T> queryPage(Map<String, Object> condition,

                            Integer currentPage, Integer pageSize) {

 

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

 

                   try {

 

                            if (condition == null) {

 

                                     condition = new HashMap<String, Object>();

 

                            }

 

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

                                               * pager.getPageSize());

 

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

 

                            List<T> 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<String, Object> 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<T> queryList(Map<String, Object> condition, String orderBy,

                            String sortBy) {

 

                   if (condition == null) {

                            condition = new HashMap<String, Object>();

                            condition.put("orderBy", orderBy);

                            condition.put("sortBy", sortBy);

                   }

 

                   return (List<T>)getSqlSession().selectList(

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

         }

 

         /**

          * 通过条件查询一条

          */

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

         public T queryOne(Map<String, Object> 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<String, Object> condition = new HashMap<String, Object>();

                   condition.put(property, value);

                   return (T)getSqlSession().selectOne(

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

         }

 

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

         public List<T> findList(String property, Object value) {

                   Map<String, Object> condition = new HashMap<String, Object>();

                   condition.put(property, value);

                   return getSqlSession().selectList(

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

         }

 

         public Class<T> getEntityClass() {

                   return entityClass;

         }

        

         public Integer selectMaxId() {

                   return getSqlSession().selectOne(

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

         }

 

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

         public void deleteByCondition(Map<String, Object> condition) {

 

                   getSqlSession().delete(

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

 

         }

 

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

         public void deleteByProperty(String property, Object value) {

                   Map<String, Object> condition = new HashMap<String, Object>();

                   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<T> selectList(String mapperId, Object obj) {

                   return getSqlSession().selectList(

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

         }

 

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

         public List<T> insertList(List<T> entities) {

                  return getSqlSession().selectList(

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

         }

 

         /*

         public DetailsPager<T> queryDetailsPage(Map<String, Object> condition, PK id) {

 

                   T currentObj = fetch(id);

 

                   if (currentObj != null) {

 

                            List<PK> ids = getSqlSession().selectList(

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

 

                            int currentObjIndex = ids.indexOf(id);

 

                            DetailsPager<T> page = new DetailsPager<T>(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<T> like(String property, Object value) {

                   Map<String, Object> condition = new HashMap<String, Object>();

                   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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

         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

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
2月前
|
SQL 关系型数据库 MySQL
mysql主从复制概述和配置
【10月更文挑战第22天】MySQL 主从复制是一种将主服务器的数据复制到一个或多个从服务器的技术,实现读写分离,提高系统性能和可用性。主服务器记录变更日志,从服务器通过 I/O 和 SQL 线程读取并应用这些变更。适用于读写分离、数据备份和恢复、数据分析等场景。配置步骤包括修改配置文件、创建复制用户、配置从服务器连接主服务器并启动复制进程。
|
2月前
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
48 4
|
28天前
|
JavaScript 前端开发 开发工具
web项目规范配置(husky、eslint、lint-staged、commit)
通过上述配置,可以确保在Web项目开发过程中自动进行代码质量检查和规范化提交。Husky、ESLint、lint-staged和Commitlint共同作用,使得每次提交代码之前都会自动检查代码风格和语法问题,防止不符合规范的代码进入代码库。这不仅提高了代码质量,还保证了团队协作中的一致性。希望这些配置指南能帮助你建立高效的开发流程。
36 5
|
1月前
|
存储 SQL 关系型数据库
2024Mysql And Redis基础与进阶操作系列(1)作者——LJS[含MySQL的下载、安装、配置详解步骤及报错对应解决方法]
Mysql And Redis基础与进阶操作系列(1)之[MySQL的下载、安装、配置详解步骤及报错对应解决方法]
|
1月前
|
关系型数据库 MySQL Linux
在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,包括准备工作、下载源码、编译安装、配置 MySQL 服务、登录设置等。
本文介绍了在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,包括准备工作、下载源码、编译安装、配置 MySQL 服务、登录设置等。同时,文章还对比了编译源码安装与使用 RPM 包安装的优缺点,帮助读者根据需求选择最合适的方法。通过具体案例,展示了编译源码安装的灵活性和定制性。
89 2
|
2月前
|
SQL 关系型数据库 MySQL
Mysql中搭建主从复制原理和配置
主从复制在数据库管理中广泛应用,主要优点包括提高性能、实现高可用性、数据备份及灾难恢复。通过读写分离、从服务器接管、实时备份和地理分布等机制,有效增强系统的稳定性和数据安全性。主从复制涉及I/O线程和SQL线程,前者负责日志传输,后者负责日志应用,确保数据同步。配置过程中需开启二进制日志、设置唯一服务器ID,并创建复制用户,通过CHANGE MASTER TO命令配置从服务器连接主服务器,实现数据同步。实验部分展示了如何在两台CentOS 7服务器上配置MySQL 5.7主从复制,包括关闭防火墙、配置静态IP、设置域名解析、配置主从服务器、启动复制及验证同步效果。
Mysql中搭建主从复制原理和配置
|
2月前
|
关系型数据库 MySQL Java
Django学习二:配置mysql,创建model实例,自动创建数据库表,对mysql数据库表已经创建好的进行直接操作和实验。
这篇文章是关于如何使用Django框架配置MySQL数据库,创建模型实例,并自动或手动创建数据库表,以及对这些表进行操作的详细教程。
74 0
Django学习二:配置mysql,创建model实例,自动创建数据库表,对mysql数据库表已经创建好的进行直接操作和实验。
|
2月前
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
123 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
2月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
60 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
2月前
|
前端开发 Java Apache
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
本文详细讲解了如何整合Apache Shiro与Spring Boot项目,包括数据库准备、项目配置、实体类、Mapper、Service、Controller的创建和配置,以及Shiro的配置和使用。
387 1
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个

推荐镜像

更多