1. 程式人生 > >spring+Mybatis+通用mapper+分頁助手+restful風格的編寫使用案例

spring+Mybatis+通用mapper+分頁助手+restful風格的編寫使用案例

一、基本環境

IDE:Eclipse Java EE IDE for Web Developers Version: Neon Release (4.6.0)
JDK:1.8
Mysql:mysql-5.6.24
maven:maven3.3.9
Tomcat:tomcat9
二、專案基本搭建
1、建立資料庫
首先建立一個測試資料庫mybatis,在該資料庫中建立一個數據表tb_user,建立語句如下:
CREATE TABLE `tb_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) DEFAULT NULL COMMENT '使用者名稱',
  `password` varchar(100) DEFAULT NULL COMMENT '密碼',
  `name` varchar(100) DEFAULT NULL COMMENT '姓名',
  `age` int(10) DEFAULT NULL COMMENT '年齡',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性別,1男性,2女性',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `created` datetime DEFAULT NULL COMMENT '建立時間',
  `updated` datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8
2、建立maven的父專案
建立一個pom工程:kang-parent,其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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.kang.parent</groupId>
	<artifactId>kang-parent</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>


	<!-- 集中定義依賴版本號 -->
	<properties>
		<junit.version>4.10</junit.version>
		<spring.version>4.1.3.RELEASE</spring.version>
		<mybatis.version>3.2.8</mybatis.version>
		<mybatis.spring.version>1.2.2</mybatis.spring.version>
		<mybatis.paginator.version>1.2.15</mybatis.paginator.version>
		<mysql.version>5.1.32</mysql.version>
		<slf4j.version>1.6.4</slf4j.version>
		<jackson.version>2.4.2</jackson.version>
		<druid.version>1.0.9</druid.version>
		<httpclient.version>4.3.5</httpclient.version>
		<jstl.version>1.2</jstl.version>
		<servlet-api.version>2.5</servlet-api.version>
		<jsp-api.version>2.0</jsp-api.version>
		<joda-time.version>2.5</joda-time.version>
		<commons-lang3.version>3.3.2</commons-lang3.version>
		<commons-io.version>1.3.2</commons-io.version>
	</properties>


	<dependencyManagement>
		<dependencies>
			<!-- 單元測試 -->
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>${junit.version}</version>
				<scope>test</scope>
			</dependency>


			<!-- Spring -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</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-webmvc</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-jdbc</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-aspects</artifactId>
				<version>${spring.version}</version>
			</dependency>


			<!-- Mybatis -->
			<dependency>
				<groupId>org.mybatis</groupId>
				<artifactId>mybatis</artifactId>
				<version>${mybatis.version}</version>
			</dependency>
			<dependency>
				<groupId>org.mybatis</groupId>
				<artifactId>mybatis-spring</artifactId>
				<version>${mybatis.spring.version}</version>
			</dependency>


			<!-- MySql -->
			<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>${mysql.version}</version>
			</dependency>


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


			<!-- Jackson Json處理工具包 -->
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-databind</artifactId>
				<version>${jackson.version}</version>
			</dependency>


			<!-- 連線池 -->
			<dependency>
				<groupId>com.jolbox</groupId>
				<artifactId>bonecp-spring</artifactId>
				<version>0.8.0.RELEASE</version>
			</dependency>


			<!-- httpclient -->
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
				<version>${httpclient.version}</version>
			</dependency>


			<!-- JSP相關 -->
			<dependency>
				<groupId>jstl</groupId>
				<artifactId>jstl</artifactId>
				<version>${jstl.version}</version>
			</dependency>
			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>servlet-api</artifactId>
				<version>${servlet-api.version}</version>
				<scope>provided</scope>
			</dependency>
			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>jsp-api</artifactId>
				<version>${jsp-api.version}</version>
				<scope>provided</scope>
			</dependency>


			<!-- 時間操作元件 -->
			<dependency>
				<groupId>joda-time</groupId>
				<artifactId>joda-time</artifactId>
				<version>${joda-time.version}</version>
			</dependency>


			<!-- Apache工具元件 -->
			<dependency>
				<groupId>org.apache.commons</groupId>
				<artifactId>commons-lang3</artifactId>
				<version>${commons-lang3.version}</version>
			</dependency>
			<dependency>
				<groupId>org.apache.commons</groupId>
				<artifactId>commons-io</artifactId>
				<version>${commons-io.version}</version>
			</dependency>


		</dependencies>
	</dependencyManagement>


	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<!-- 資原始檔拷貝外掛 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.7</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- java編譯外掛 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!-- 配置Tomcat外掛 -->
				<plugin>
					<groupId>org.apache.tomcat.maven</groupId>
					<artifactId>tomcat7-maven-plugin</artifactId>
					<version>2.2</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

3、建立子專案
建立一個war工程kang-usermanage,其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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.kang.parent</groupId>
		<artifactId>kang-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<groupId>com.kang.usermanage</groupId>
	<artifactId>kang-usermanage</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>war</packaging>


	<dependencies>
		<!-- 單元測試 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
		</dependency>
		<!-- Mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
		</dependency>


		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>3.7.5</version>
		</dependency>
		<dependency>
			<groupId>com.github.jsqlparser</groupId>
			<artifactId>jsqlparser</artifactId>
			<version>0.9.1</version>
		</dependency>


		<!-- 通用Mapper -->
		<dependency>
			<groupId>com.github.abel533</groupId>
			<artifactId>mapper</artifactId>
			<version>2.3.4</version>
		</dependency>


		<!-- MySql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
		</dependency>
		<!-- Jackson Json處理工具包 -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<!-- 連線池 -->
		<dependency>
			<groupId>com.jolbox</groupId>
			<artifactId>bonecp-spring</artifactId>
		</dependency>
		<!-- JSP相關 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- Apache工具元件 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>
	</dependencies>


	<build>
		<!-- 配置外掛 -->
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<url>http://localhost:8081/manager/text</url>
					<server>tomcat7</server>
					<port>8081</port>
					<path>/</path>
					<username>tomcat</username>
					<password>123456</password>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

三、配置檔案詳解
1、mysql的外部屬性檔案:jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.username=root
jdbc.password=root
2、編寫Mybatis的全域性配置檔案:mybatis/mybatis-config.xml
在這裡集成了分頁助手和通用mapper。注意,分頁助手的配置要放在通用mapper之前。
<?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>


	<plugins>
		<!-- 配置分頁助手 -->
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<property name="dialect" value="mysql" />
			<!-- 設定為true時,使用RowBounds分頁會進行count查詢 -->
			<property name="rowBoundsWithCount" value="true" />
		</plugin>


		<!-- 通用Mapper -->
		<plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
			<!--主鍵自增回寫方法,預設值MYSQL,詳細說明請看文件 -->
			<property name="IDENTITY" value="MYSQL" />
			<!--通用Mapper介面,多個通用介面用逗號隔開 -->
			<property name="mappers" value="com.github.abel533.mapper.Mapper" />
		</plugin>
	</plugins>


</configuration>
3、編寫spring整合Mybatis的xml檔案。spring/applicationContext-mybatis.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


	<bean class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定資料來源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 指定mybatis的全域性配置檔案 -->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
		<!-- 指定mapper.xml檔案,掃描所有的檔案 -->
		<property name="mapperLocations" value="classpath:mybatis/mappers/**/*.xml"/>
		<!-- 指定別名包 -->
		<property name="typeAliasesPackage" value="com.kang.mybatis.pojo"/>
	</bean>
	
	<!-- 定義Mapper介面的掃描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.kang.mybatis.mapper"/>
	</bean>


</beans>
4、編寫spring的事務管理配置檔案spring/applicationContext-transaction.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<!-- 定義事務管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>


	<!-- 定義事務策略 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!--所有以query開頭的方法都是隻讀的 -->
			<tx:method name="query*" read-only="true" />
			<!--其他方法使用預設事務策略 -->
			<tx:method name="*" />
		</tx:attributes>
	</tx:advice>


	<aop:config>
		<!--pointcut元素定義一個切入點,execution中的第一個星號 用以匹配方法的返回型別,
			這裡星號表明匹配所有返回型別。 com.abc.dao.*.*(..)表明匹配com.kang.mybatis.service包下的所有類的所有 
			方法 -->
		<aop:pointcut id="myPointcut" expression="execution(* com.kang.mybatis.service.*.*(..))" />
		<!--將定義好的事務處理策略應用到上述的切入點 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
	</aop:config>
	
</beans>
5、編寫spring關於bean的配置檔案spring/applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


	<!-- 使用spring自帶的佔位符替換功能 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<!-- 允許JVM引數覆蓋 -->
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<!-- 忽略沒有找到的資原始檔 -->
		<property name="ignoreResourceNotFound" value="true" />
		<!-- 配置資原始檔 -->
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
	
	<!-- 掃描包 -->
	<context:component-scan base-package="com.kang"/>


	 <!-- 定義資料來源 -->
	<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
		destroy-method="close">
		<!-- 資料庫驅動 -->
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<!-- 相應驅動的jdbcUrl -->
		<property name="jdbcUrl" value="${jdbc.url}" />
		<!-- 資料庫的使用者名稱 -->
		<property name="username" value="${jdbc.username}" />
		<!-- 資料庫的密碼 -->
		<property name="password" value="${jdbc.password}" />
		<!-- 檢查資料庫連線池中空閒連線的間隔時間,單位是分,預設值:240,如果要取消則設定為0 -->
		<property name="idleConnectionTestPeriod" value="60" />
		<!-- 連線池中未使用的連結最大存活時間,單位是分,預設值:60,如果要永遠存活設定為0 -->
		<property name="idleMaxAge" value="30" />
		<!-- 每個分割槽最大的連線數 -->
		<!-- 
			判斷依據:請求併發數
		 -->
		<property name="maxConnectionsPerPartition" value="100" />
		<!-- 每個分割槽最小的連線數 -->
		<property name="minConnectionsPerPartition" value="5" />
	</bean>


</beans>
6、編寫springMVC的xml配置檔案spring/kang-usermanage-servlet.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 定義註解驅動 -->
	<mvc:annotation-driven/>
	
	<!-- 定義Controller的掃描包 -->
	<context:component-scan base-package="com.kang.mybatis.controller"/>
	
	<!-- 定義試圖解析器 -->
	<!-- 
		Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" -> "/WEB-INF/jsp/test.jsp" 
	 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>


</beans>
7、編寫web.xml完成專案整體配置
<?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"
	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>kang-usermanage</display-name>


	<!-- 載入spring的配置檔案 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/applicationContext*.xml</param-value>
	</context-param>


	<!--Spring的ApplicationContext 載入 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>


	<!-- 編碼過濾器,以UTF8編碼,避免中文亂碼 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!-- 新增spring對REST風格的支援 -->
	<filter>
		<filter-name>HttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 將POST請求轉化為DELETE或者是PUT 要用_method指定真正的請求引數 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>




	<!-- 配置SpringMVC框架入口 -->
	<servlet>
		<servlet-name>kang-usermanage</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/kang-usermanage-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>




	<servlet-mapping>
		<servlet-name>kang-usermanage</servlet-name>
		<!-- 可用: *.xxx,/,/xxx/* . 不可用:/* -->
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>


	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>


</web-app>
8、新增日誌屬性檔案log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.logger.com.taotao = DEBUG
log4j.logger.org.mybatis = DEBUG


log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
四、業務程式碼編寫
1、通用頁面跳轉
package com.kang.mybatis.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


//通用的頁面跳轉Controller
@RequestMapping("page")
@Controller
public class PageController {


    @RequestMapping(value = "{pageName}", method = RequestMethod.GET)
    public String toPage(@PathVariable("pageName") String pageName) {
        return pageName;
    }


}


2、封裝EasyUIResult
package com.kang.mybatis.bean;


import java.util.List;


public class EasyUIResult {


    private Long total;


    private List<?> rows;


    public EasyUIResult() {


    }


    public EasyUIResult(Long total, List<?> rows) {
        this.total = total;
        this.rows = rows;
    }


    public Long getTotal() {
        return total;
    }


    public void setTotal(Long total) {
        this.total = total;
    }


    public List<?> getRows() {
        return rows;
    }


    public void setRows(List<?> rows) {
        this.rows = rows;
    }


}


3、編寫mapper介面,此介面繼承通用mapper
package com.kang.mybatis.mapper;


import com.github.abel533.mapper.Mapper;
import com.kang.mybatis.pojo.User;


public interface NewUserMapper extends Mapper<User>{


}


4、新增pojo類
package com.kang.mybatis.pojo;


import java.util.Date;


import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Table(name = "tb_user")
public class User {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    // 使用者名稱
    private String userName;


    // 密碼
    private String password;


    // 姓名
    private String name;


    // 年齡
    private Integer age;


    // 性別,1男性,2女性
    private Integer sex;


    // 出生日期
    private Date birthday;


    // 建立時間
    private Date created;


    // 更新時間
    private Date updated;


    public Long getId() {
        return id;
    }


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


    public String getuserName() {
        return userName;
    }


    public void setuserName(String userName) {
        this.userName = userName;
    }


    public String getPassword() {
        return password;
    }


    public void setPassword(String password) {
        this.password = password;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public Integer getAge() {
        return age;
    }


    public void setAge(Integer age) {
        this.age = age;
    }


    public Integer getSex() {
        return sex;
    }


    public void setSex(Integer sex) {
        this.sex = sex;
    }


    public Date getBirthday() {
        return birthday;
    }


    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }


    public Date getCreated() {
        return created;
    }


    public void setCreated(Date created) {
        this.created = created;
    }


    public Date getUpdated() {
        return updated;
    }


    public void setUpdated(Date updated) {
        this.updated = updated;
    }


    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", name=" + name
                + ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + ", created=" + created
                + ", updated=" + updated + "]";
    }


}


5、編寫service方法
package com.kang.mybatis.service;


import java.util.Date;
import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.github.abel533.entity.Example;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kang.mybatis.bean.EasyUIResult;
import com.kang.mybatis.mapper.NewUserMapper;
import com.kang.mybatis.pojo.User;


@Service
public class NewUserService {


    @Autowired
    private NewUserMapper newUserMapper;


    public EasyUIResult queryUserList(Integer page, Integer rows) {
        // 設定分頁引數
        PageHelper.startPage(page, rows);


        // 設定查詢條件
        Example example = new Example(User.class);
        example.setOrderByClause("created DESC"); // 設定排序條件
        List<User> users = this.newUserMapper.selectByExample(example);


        PageInfo<User> pageInfo = new PageInfo<User>(users);
        return new EasyUIResult(pageInfo.getTotal(), pageInfo.getList());
    }


    public User queryUserById(Long id) {
        return this.newUserMapper.selectByPrimaryKey(id);
    }


    public void saveUser(User user) {
        user.setCreated(new Date());
        user.setUpdated(new Date());
        this.newUserMapper.insertSelective(user);
    }


    public void updateUser(User user) {
        this.newUserMapper.updateByPrimaryKeySelective(user);
    }


    public void deleteUserById(Long id) {
        this.newUserMapper.deleteByPrimaryKey(id);
    }


}


6、編寫controller方法
package com.kang.mybatis.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.kang.mybatis.bean.EasyUIResult;
import com.kang.mybatis.pojo.User;
import com.kang.mybatis.service.NewUserService;


@RequestMapping("user")
@Controller
public class UserController {


    // @Autowired
    // private UserService userService;


    @Autowired
    private NewUserService userService;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public EasyUIResult queryUserList(@RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows) {
        return this.userService.queryUserList(page, rows);
    }
    
    //查詢資料
    @RequestMapping(value="{userId}",method=RequestMethod.GET)
    public ResponseEntity<User> quseryUserById(@PathVariable("userId") Long userId){
    	try {
			User user=this.userService.queryUserById(userId);
			if(null==user){
				//返回404資源不存在
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			}
			//返回200,成功
			//return ResponseEntity.status(HttpStatus.OK).body(user);
			return ResponseEntity.ok(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	//查詢出錯,返回500
    	return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    
    //新增資料
    @RequestMapping(method=RequestMethod.POST)
    public ResponseEntity<Void> saveUser(User user){
    	try {
			this.userService.saveUser(user);;
			return ResponseEntity.status(HttpStatus.CREATED).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	//查詢出錯,返回500
    	return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    
    //更新資料
    @RequestMapping(method=RequestMethod.PUT)
    public ResponseEntity<Void> updateUser(User user){
    	try {
			this.userService.updateUser(user);
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	//查詢出錯,返回500
    	return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    
    //刪除資料
    @RequestMapping(method=RequestMethod.DELETE)
    public ResponseEntity<Void> deleteUser(@RequestParam(value="id",defaultValue="0") Long id){
    	try {
    		if(id.intValue()==0){
    			//引數有誤
    			return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    		}
    		this.userService.deleteUserById(id);
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	//查詢出錯,返回500
    	return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }


}


7、編寫對通用mapper的單元測試檔案
package com.kang.mabatis.test;




import static org.junit.Assert.fail;


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


import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.github.abel533.entity.Example;
import com.kang.mybatis.mapper.NewUserMapper;
import com.kang.mybatis.pojo.User;
public class NewUserMapperTest {


    private NewUserMapper newUserMapper;


    @Before
    public void setUp() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "classpath:spring/applicationContext*.xml");
        this.newUserMapper = applicationContext.getBean(NewUserMapper.class);
    }


    @Test
    public void testSelectOne() {
        User record = new User();
        // 設定查詢條件
        record.setuserName("zhangsan");
        record.setPassword("123456");
        User user = this.newUserMapper.selectOne(record);
        System.out.println(user);
    }


    @Test
    public void testSelect() {
        User record = new User();
        // 設定查詢條件
        record.setuserName("zhangsan");
        List<User> list = this.newUserMapper.select(record);
        for (User user : list) {
            System.out.println(user);
        }
    }


    @Test
    public void testSelectCount() {
        System.out.println(this.newUserMapper.selectCount(null));
    }


    @Test
    public void testSelectByPrimaryKey() {
    	//注意selectByPrimaryKey的輸入引數必須是Long型,不能是string型別。new Long(1)
        User user = this.newUserMapper.selectByPrimaryKey(new Long(1));
        System.out.println(user);
    } 
    
    @Test
    public void testInsert() {
        User record = new User();
        // 設定查詢條件
        record.setuserName("test_username_3");
        //record.setAge(20);
        //record.setBirthday(new Date());
        record.setCreated(new Date());
        //record.setName("test_name_1");
        //record.setPassword("123456");
        record.setSex(1);
        record.setUpdated(new Date());
        //使用所有的欄位作為插入語句的欄位
        int count = this.newUserMapper.insert(record);
        System.out.println(count);
        System.out.println(record.getId());
    }


    @Test
    public void testInsertSelective() {
        User record = new User();
        // 設定查詢條件
        record.setuserName("test_username_2");
        //record.setAge(20);
       // record.setBirthday(new Date());
        record.setCreated(new Date());
       // record.setName("test_name_1");
       // record.setPassword("123456");
        record.setSex(1);
        record.setUpdated(new Date());
        //將不為null的欄位作為插入語句的欄位
        int count = this.newUserMapper.insertSelective(record);
        System.out.println(count);
        System.out.println(record.getId());
    }


    @Test
    public void testDelete() {
//        this.newUserMapper.delete(null);
    }


    @Test
    public void testDeleteByPrimaryKey() {
        System.out.println(this.newUserMapper.deleteByPrimaryKey(9L));
    }


    @Test
    public void testUpdateByPrimaryKey() {
        fail("Not yet implemented");
    }


    @Test
    public void testUpdateByPrimaryKeySelective() {
        User record = new User();
        record.setId(1L);
        record.setAge(24);
        this.newUserMapper.updateByPrimaryKeySelective(record);
    }


    @Test
    public void testSelectCountByExample() {
        fail("Not yet implemented");
    }


    @Test
    public void testDeleteByExample() {
        fail("Not yet implemented");
    }


    @Test
    public void testSelectByExample() {
        Example example = new Example(User.class);
        List<Object> values = new ArrayList<Object>();
        values.add(1L);
        values.add(2L);
        values.add(3L);
        //批量查詢
        //example.createCriteria().andIn("id", values);
        //單個查詢
        example.createCriteria().andEqualTo("id", 1L);
        List<User> list = this.newUserMapper.selectByExample(example);
        
        for (User user : list) {
            System.out.println(user);
        }
    }


    @Test
    public void testUpdateByExampleSelective() {
        fail("Not yet implemented");
    }


    @Test
    public void testUpdateByExample() {
        fail("Not yet implemented");
    }


}


五、專案測試
1、查詢所有資訊
資料庫內容如下:

在瀏覽器中輸入: http://127.0.0.1:8081/rest/page/users
得到頁面如下:前端頁面基於easyUI實現,資料按照更新時間排序。
 
2、restful的相關測試
(1)使用get獲取資料
 


(2)使用post提交資料
 


資料庫資料:
 
(3)使用put更新資料
 


資料庫資料:
 


(4)使用delete刪除資料
 
資料庫資料:
 

相關部落格:

附github專案原始碼地址:github原始碼