SpringMVC整合Mybatis

SpringMVC + springfox + MyBatis的系列文章,在此篇也基本可以定調了。故此這篇會給出完整代碼。

1.完整jar包

----------------SpringMVC jar START--------------------
spring-aop-4.3.4.RELEASE.jar
spring-beans-4.3.4.RELEASE.jar
spring-context-4.3.4.RELEASE.jar
spring-core-4.3.4.RELEASE.jar
spring-expression-4.3.4.RELEASE.jar
spring-web-4.3.4.RELEASE.jar
spring-webmvc-4.3.4.RELEASE.jar
common-logging-1.0.4.jar
----------------SpringMVC整合springfox的jar START--------------------
classmate-1.3.3.jar
guava-19.0.jar
jackson-annotations-2.8.4.jar
jackson-core-2.8.7.jar
jackson-databind-2.8.7.jar
slf4j-api-1.7.24.jar
spring-plugin-core-1.2.0.RELEASE.jar
spring-plugin-metadata-1.2.0.RELEASE.jar
springfox-core-2.6.1.jar
springfox-schema-2.6.1.jar
springfox-spi-2.6.1.jar
springfox-spring-web-2.6.1.jar
springfox-swagger-common-2.6.1.jar
springfox-swagger-ui-2.6.1.jar
springfox-swagger2-2.6.1.jar
swagger-annotations-1.5.10.jar
swagger-models-1.5.10.jar
----------------SpringMVC整合MyBatis的jar START--------------------
mysql-connector-java-5.1.40-bin.jar
junit-4.12.jar
hamcreate-core-1.3.jar
hamcreate-library-1.3.jar
spring-jdbc-4.3.4.RELEASE.jar
spring-tx-4.3.4.RELEASE.jar
druid-1.0.27.jar
mybatis-3.4.2.jar
mybatis-spring-1.3.1.jar

2.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
		http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
		id="WebApp_ID" version="3.1">
  <display-name>bphss-sample</display-name>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 加載spring容器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-config.xml</param-value>
  </context-param>
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 解決post亂碼 -->
  <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>
  
  <!-- springmvc的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- contextConfigLocation不是必須的;
  	     如果不配置contextConfigLocation, 
  	  springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml"
     -->
    <init-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

3.springmvc-config.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.3.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  
  <!-- 開啓springmvc註解 -->
  <mvc:annotation-driven />
  
  <!-- 自動掃描包 -->
  <context:component-scan base-package="com.chensan" />
  
  <!-- 注入swagger -->
  <bean class="com.chensan.config.Swagger2Config" />
  <!-- Enables swgger ui -->
  <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html" />
  <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**" />
  
  <!-- 
  <mvc:resources location="/WEB-INF/static/" mapping="/static/**"/>
   -->
   
  <!-- 配置視圖解析器:如何把Handler方法返回值解析爲實際的物理視圖 -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
  </bean>
</beans>

4.spring-config.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:tx="http://www.springframework.org/schema/tx" 
  xmlns:aop="http://www.springframework.org/schema/aop" 
  xmlns:context="http://www.springframework.org/schema/context" 
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  
  <!-- 引入配置文件 -->
  <bean id="propertyConfigurer"  
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="location" value="classpath:db-config.properties" />  
  </bean>
  
  <!-- 數據源配置 -->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
	init-method="init" destroy-method="close">
	<property name="driverClassName" value="${driver}" />
	<property name="url" value="${url}" />
	<property name="username" value="${username}" />
	<property name="password" value="${password}" />
	
	<!-- 配置初始化大小、最小、最大 -->
	<property name="initialSize" value="${initialSize}" />
	<property name="maxActive" value="${maxActive}" />
	<property name="minIdle" value="${minIdle}" />

	<!-- 配置獲取連接等待超時的時間 -->
	<property name="maxWait" value="${maxWait}" />

	<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒 -->
	<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />

	<!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
	<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />

	<property name="validationQuery" value="${validationQuery}" />
	<property name="testWhileIdle" value="${testWhileIdle}" />
	<property name="testOnBorrow" value="${testOnBorrow}" />
	<property name="testOnReturn" value="${testOnReturn}" />

	<!-- 打開PSCache,並且指定每個連接上PSCache的大小 -->
	<property name="poolPreparedStatements" value="${poolPreparedStatements}" />
	<property name="maxPoolPreparedStatementPerConnectionSize"
	  value="${maxPoolPreparedStatementPerConnectionSize}" />
  </bean>
 
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<!-- 配置mybatis配置文件的位置 -->
	<property name="configLocation" value="classpath:mybatis-config.xml" />
	<!-- 配置掃描Mapper XML的位置 -->
	<property name="mapperLocations" value="classpath*:com/chensan/mybatis/**/*.xml" />
  </bean>

  <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
	<constructor-arg ref="sqlSessionFactory" />
  </bean>
</beans>

5.db-config.properties

## MySQL
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bphss?useSSL=true
username=root
password=123456

## Oracle
## oracle=jdbc:oracle:thin:@10.20.149.85:1521:ocnauto


#定義初始連接數 ,缺省值:0
initialSize=0
#定義最大連接池數量,缺省值:8
maxActive=20
#定義最小空閒
minIdle=1
#定義最大空閒,缺省值:8;已經不再使用,配置了也沒效果
## maxIdle=20
## 定義最長等待時間,單位:毫秒;
## 配置了maxWait之後,缺省啓用公平鎖,併發效率會有所下降, 
## 如果需要可以通過配置useUnfairLock屬性爲true使用非公平鎖。
maxWait=60000
#配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
timeBetweenEvictionRunsMillis=60000
#配置一個連接在池中最小生存的時間,單位是毫秒
minEvictableIdleTimeMillis=300000

validationQuery=SELECT 'x'
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
#是否緩存preparedStatement,也就是PSCache。 缺省爲false;
#PSCache對支持遊標的數據庫性能提升巨大,比如說oracle。 
#在mysql5.5以下的版本中沒有PSCache功能。
#可通過監控界面發現PSCache有緩存命中率記錄。
poolPreparedStatements=false
#指定每個連接上PSCache的大小
maxPoolPreparedStatementPerConnectionSize=20

6.mybatis-config.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="cacheEnabled" value="true" />
	<setting name="lazyLoadingEnabled" value="true" />
	<setting name="multipleResultSetsEnabled" value="true" />
	<setting name="useColumnLabel" value="true" />
	<setting name="useGeneratedKeys" value="true" />
	<setting name="defaultExecutorType" value="SIMPLE" />
	<setting name="defaultStatementTimeout" value="2" />
	<setting name="callSettersOnNulls" value="true"/>
  </settings>
  <typeAliases>
	<package name="com.chensan.entity" />
  </typeAliases>
  <mappers></mappers>
</configuration>

7.Entity(省略setter、getter方法節省篇幅)

package com.chensan.entity.sys;

import java.io.Serializable;

public class UserMedic implements Serializable {  
    private static final long serialVersionUID = 1L;
    
    /**
     * 主鍵ID. 
     */
    private Integer id;   
                       
    /** 
     * 登錄名. 
     */  
    private String loginName;     
                       
    /** 
     * 登錄密碼. 
     */  
    private String loginPwd;      
           
    /** 
     * 姓名. 
     */  
    private String userName; 
}

8.IBaservice

package com.chensan.common.service;

import java.util.List;
import java.util.Map;

import com.chensan.common.repository.ProcResult;

public interface IBaseService<T, K> {
	/**
	 * 新增實體對象.
	 * @param entity
	 *            要新增的實體對象
	 * @return 返回受影響行數,插入成功返回1。
	 */
	public int insert(T entity);

	/**
	 * 批量插入實體對象.
	 * @param list
	 *            要插入的實體對象集合
	 * @return 返回受影響行數,成功則返回插入數量。
	 */
	public int batchInsert(List<T> list);

	/**
	 * 部分更新.
	 * @param entity
	 *            要更新的實體對象.
	 */
	public int updateById(T entity);

	/**
	 * 部分更新.
	 * @param entity
	 *            要更新的實體對象.<br>
	 *            一般使用方法:new一個新的實體對象,對需要更新的字段和主鍵賦值,然後傳入進行更新。
	 */
	public int updateSelectiveById(T entity);

	/**
	 * 根據id主鍵刪除實體對象.
	 * @param id
	 *            主鍵id
	 * @return 返回刪除的行數。
	 */
	public int deleteById(K id);

	/**
	 * 根據id批量刪除.
	 * @param ids
	 *            要刪除實體對象的主鍵
	 * @return 返回刪除的行數。
	 */
	public int deleteByIds(List<K> ids);

	/**
	 * 根據主鍵id查詢數據.
	 * @param id
	 *            主鍵id
	 * @return 返回該id對象的數據。
	 */
	public T queryById(K id);

	/**
	 * 根據多個id查詢.
	 * @param ids
	 *            id列表
	 * @return 返回指定id的實體對象列表。
	 */
	public List<T> queryByIds(List<K> ids);

	/**
	 * 查詢數數據庫中記錄總條數.
	 * @param where
	 *            查詢條件。如id=1 and name like '%jhon'
	 * @return 返回滿足查詢條件的記錄總條數。
	 */
	public Long queryCount(String where);

	/**
	 * 返回數據庫中所有記錄.
	 * @return 返回數據表中所有記錄。
	 */
	public List<T> queryAll();

	/**
	 * 條件分頁查詢.
	 * @param start
	 *            數據庫查詢記錄偏移值
	 * @param pageSize
	 *            每頁數據條數
	 * @param totlaCount
	 *            滿足條件的記錄條數
	 * @param where
	 *            查詢條件。如id=1 and name like '%jhon'
	 * @param order
	 *            排序條件,如time desc。
	 * @return 返回滿足條件的分頁數據 ,及數據條數。
	 */
	public ProcResult<T> queryByPage(long start, long pageSize, long totlaCount, String where, String order);

	/**
	 * 存儲過程分頁查詢.
	 * @param start
	 *            數據庫查詢記錄偏移值
	 * @param pageSize
	 *            每頁數據條數
	 * @param totlaCount
	 *            滿足條件的記錄條數
	 * @param params
	 *            查詢條件參數,存儲過程參數,不包含start、pageSize、totlaCount的其它參數。
	 * @return 返回滿足條件的分頁數據 ,及數據條數。
	 */
	public ProcResult<T> queryByPageAndProc(long start, long pageSize, long totlaCount, Map<String, Object> params);
}

9.BaserviceImpl

package com.chensan.common.service;

import java.util.List;
import java.util.Map;

import com.chensan.common.repository.BaseMapper;
import com.chensan.common.repository.ProcResult;

/**
 * Service層基類
 * @author <a href="mailto:[email protected]">chenhf</a>
 * @param <T>
 */

public abstract class BaseServiceImpl<T, K> implements IBaseService<T, K> {
	public abstract BaseMapper<T, K> getMapper();

	/**
	 * 新增實體對象.
	 * @param entity
	 *            要新增的實體對象
	 * @return 返回受影響行數,插入成功返回1。
	 */
	public int insert(T entity) {
		return getMapper().insert(entity);
	}

	/**
	 * 批量插入實體對象.
	 * @param list
	 *            要插入的實體對象集合
	 * @return 返回受影響行數,成功則返回插入數量。
	 */
	public int batchInsert(List<T> list) {
		return getMapper().batchInsert(list);
	}

	/**
	 * 部分更新.
	 * @param entity
	 *            要更新的實體對象.
	 * @return 返回更新的行數。
	 */
	public int updateById(T entity) {
		return getMapper().updateById(entity);
	}

	/**
	 * 部分更新.
	 * @param entity
	 *     要更新的實體對象.<br>
	 *     一般使用方法:new一個新的實體對象,對需要更新的字段和主鍵賦值,然後傳入進行更新。
	 * @return 返回更新的行數。
	 */
	public int updateSelectiveById(T entity) {
		return getMapper().updateSelectiveById(entity);
	}

	/**
	 * 根據id主鍵刪除實體對象.
	 * @param id
	 *            主鍵id
	 */
	public int deleteById(K id) {
		return getMapper().deleteById(id);
	}

	/**
	 * 根據id批量刪除.
	 * @param ids
	 *            要刪除實體對象的主鍵
	 * @return 返回刪除的行數。
	 */
	public int deleteByIds(List<K> ids) {
		return getMapper().deleteByIds(ids);
	}

	/**
	 * 根據主鍵id查詢數據.
	 * @param id
	 *            主鍵id
	 * @return 返回該id對象的數據。
	 */
	public T queryById(K id) {
		return getMapper().queryById(id);
	}

	/**
	 * 根據多個id查詢.
	 * @param ids
	 *            id列表
	 * @return 返回指定id的實體對象列表。
	 */
	public List<T> queryByIds(List<K> ids) {
		return getMapper().queryByIds(ids);
	}

	/**
	 * 查詢數數據庫中記錄總條數.
	 * @param where
	 *            查詢條件。如id=1 and name like '%jhon'
	 * @return 返回滿足查詢條件的記錄總條數。
	 */
	public Long queryCount(String where) {
		return getMapper().queryCount(where);
	}

	/**
	 * 獲取數據庫表中所有記錄.
	 * @return 返回數據表中所有記錄。
	 */
	public List<T> queryAll() {
		return getMapper().queryAll();
	}

	/**
	 * 條件分頁查詢.
	 * @param start
	 *            數據庫查詢記錄偏移值
	 * @param pageSize
	 *            每頁數據條數
	 * @param totlaCount
	 *            滿足條件的記錄條數
	 * @param where
	 *            查詢條件。如id=1 and name like '%jhon'
	 * @param order
	 *            排序條件,如time desc。
	 * @return 返回滿足條件的分頁數據 ,及數據條數。
	 */
	public ProcResult<T> queryByPage(long start, long pageSize, long totlaCount, String where, String order) {
		return getMapper().queryByPage(start, pageSize, totlaCount, where, order);
	}

	/**
	 * 存儲過程分頁查詢.
	 * @param start
	 *            數據庫查詢記錄偏移值
	 * @param pageSize
	 *            每頁數據條數
	 * @param totlaCount
	 *            滿足條件的記錄條數
	 * @param params
	 *            查詢條件參數,存儲過程參數,不包含start、pageSize、totlaCount的其它參數。
	 * @return 返回滿足條件的分頁數據 ,及數據條數。
	 */
	public ProcResult<T> queryByPageAndProc(long start, long pageSize, long totlaCount, Map<String, Object> params) {
		return getMapper().queryByPageAndProc(start, pageSize, totlaCount, params);
	}
}

10.IUserMedicService

package com.chensan.service.sys;

import java.util.List;

import com.chensan.common.service.IBaseService;
import com.chensan.entity.sys.UserMedic;

/**
 * UserMedic 服務接口.
 * @author <a href="mailto:[email protected]">chenhf</a><br>
 * @version v1.0 <br>
 */
public interface IUserMedicService extends IBaseService<UserMedic, Integer>{
	public UserMedic queryByNameAndPwd(UserMedic userMedic);
}
其中自定義的方法爲該實體類擴展IBaservice接口中的方法;

11.UserMedicServiceImpl

package com.chensan.serviceImpl.sys;

import java.util.List;

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

import com.chensan.common.repository.BaseMapper;
import com.chensan.common.service.BaseServiceImpl;
import com.chensan.entity.sys.UserMedic;
import com.chensan.mapper.sys.UserMedicMapper;
import com.chensan.service.sys.IUserMedicService;

/**
 * UserMedic 服務類.
 * @author <a href="mailto:[email protected]">chenhf</a>
 * @version v1.0 <br>
 */
@Service("UserMedicServiceImpl")
public class UserMedicServiceImpl extends BaseServiceImpl<UserMedic, Integer> implements IUserMedicService{
	@Autowired
	private UserMedicMapper mapper;

	@Override
	public BaseMapper<UserMedic, Integer> getMapper() {
		return this.mapper;
	}

	@Override
	public UserMedic queryByNameAndPwd(UserMedic userMedic) {
		return mapper.queryByNameAndPwd(userMedic);
	}
}
實現該實體對應接口,即實體對應的擴展方法

12.BaseMapper

package com.chensan.common.repository;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Mybatis 數據訪問基類.<br>
 * T 實體對象類型. <br>
 * K 主鍵類型.
 * @author <a href="mailto:[email protected]">chenhf</a>
 */
public class BaseMapper<T, K> {

	/**
	 * 獲取Mapper類的真實數據類型
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private Class getEntityClass() {
		Class clazz = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		return clazz;
	}

	/**
	 * 獲取數據庫操作的完全限定的名稱.<br>
	 * 如:com.chensan.mybatis.sys.UserMedic.queryById
	 * @param method
	 *            Mapper.xml配置文件中方法名稱
	 * @return 返回完全限定方法名稱
	 */
	protected String getQualifiedMethod(String method) {
		String entityClassName = getEntityClass().getName();
		String methodName = entityClassName.replace(".entity.", ".mapper.") + "Mapper." + method;
		return methodName;
	}

	protected SqlSessionTemplate sqlSessionTemplate;

	/**
	 * 設置SqlSessionTemplate. <br>
	 * 子類可以覆寫。
	 * @param sqlSessionTemplate
	 *            SqlSessionTemplate模擬
	 */
	@Autowired
	protected void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	/**
	 * 新增實體對象.
	 * @param entity
	 *            要新增的實體對象
	 */
	public int insert(T entity) {
		return sqlSessionTemplate.insert(getQualifiedMethod("insert"), entity);
	}

	public int batchInsert(List<T> list) {
		return sqlSessionTemplate.insert(getQualifiedMethod("batchInsert"), list);
	}

	/**
	 * 根據主鍵刪除實體對象.
	 * @param id
	 *            主鍵id
	 * @return 返回刪除的行數。
	 */
	public int deleteById(K id) {
		return sqlSessionTemplate.delete(getQualifiedMethod("deleteById"), id);
	}

	/**
	 * 根據id批量刪除.
	 * @param ids
	 *            要刪除實體對象的主鍵
	 * @return 返回刪除的行數。
	 */
	public int deleteByIds(List<K> ids) {
		return sqlSessionTemplate.delete(getQualifiedMethod("deleteByIds"), ids);
	}

	/**
	 * 根據id更新實體對象.
	 * @param entity
	 *            要更新的實體對象
	 * @return 返回更新的行數。
	 */
	public int updateById(T entity) {
		return sqlSessionTemplate.update(getQualifiedMethod("updateById"), entity);
	}

	/**
	 * 根據id進行部分更新.<br>
	 * 根據id更新不爲null的字段。
	 * @param entity
	 *            要更新的實體對象.<br>
	 *            new一個新的實體對象,對需要更新的字段和主鍵賦值,然後傳入進行更新。
	 */
	public int updateSelectiveById(T entity) {
		return sqlSessionTemplate.update(getQualifiedMethod("updateSelectiveById"), entity);
	}

	/**
	 * 根據id查詢.
	 * @param id
	 *            主鍵id
	 * @return 返回指定id的實體對象,如果不存在則返回null。
	 *
	 */
	public T queryById(K id) {
		return sqlSessionTemplate.selectOne(getQualifiedMethod("queryById"), id);
	}

	/**
	 * 根據多個id查詢.
	 * @param ids
	 *            id列表
	 * @return 返回指定id的實體對象列表。
	 */
	public List<T> queryByIds(List<K> ids) {
		return sqlSessionTemplate.selectList(getQualifiedMethod("queryByIds"), ids);
	}

	/**
	 * 查詢數據庫中記錄總條數.
	 * @param where
	 *            查詢條件。如id=1 and name like '%jhon'
	 * @return 返回滿足查詢條件的記錄總條數。
	 *
	 */
	public Long queryCount(String where) {
		return sqlSessionTemplate.selectOne(getQualifiedMethod("queryCount"), where);
	}

	/**
	 * 查詢數據庫表中所有記錄.
	 * @return 返回表中所有記錄。
	 */
	public List<T> queryAll() {
		return sqlSessionTemplate.selectList(getQualifiedMethod("queryAll"));
	}

	/**
	 * 條件分頁查詢.
	 * @param start
	 *            數據庫查詢記錄偏移值
	 * @param pageSize
	 *            每頁數據條數
	 * @param totlaCount
	 *            滿足條件的記錄條數
	 * @param where
	 *            查詢條件。如id=1 and name like '%jhon'
	 * @param order
	 *            排序條件,如time desc。
	 * @return 返回滿足條件的分頁數據 ,及數據條數。
	 */
	public ProcResult<T> queryByPage(long start, long pageSize, long totlaCount, String where, String order) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("where", where);
		map.put("order", order);

		Long count = queryCount(where);
		List<T> list = sqlSessionTemplate.selectList(getQualifiedMethod("queryByPage"), map);

		ProcResult<T> result = new ProcResult<T>();
		result.setCount(count);
		result.setData(list);

		return result;
	}

	/**
	 * 存儲過程分頁查詢.
	 * @param start
	 *            數據庫查詢記錄偏移值
	 * @param pageSize
	 *            每頁數據條數
	 * @param totlaCount
	 *            滿足條件的記錄條數
	 * @param params
	 *            查詢條件參數,存儲過程參數,不包含start、pageSize、totlaCount的其它參數。
	 * @return 返回滿足條件的分頁數據 ,及數據條數。
	 */
	public ProcResult<T> queryByPageAndProc(long start, long pageSize, long count, Map<String, Object> params) {
		params.put("startIndex", start);
		params.put("pageSize", pageSize);
		params.put("totalCount", count);

		List<T> list = sqlSessionTemplate.selectList(getQualifiedMethod("queryByPageAndProc"), params);
		Object totlaCount = params.get("totalCount");

		Long lCount = totlaCount == null ? 0 : (Long) totlaCount;

		ProcResult<T> result = new ProcResult<T>();
		result.setCount(lCount);
		result.setData(list);

		return result;
	}
}

13.UserMedicMapper

package com.chenUserMedicMappersan.mapper.sys;

import java.util.List;

import org.springframework.stereotype.Component;

import com.chensan.common.repository.BaseMapper;
import com.chensan.entity.sys.UserMedic;

/**
 * UserMedic 數據訪問類.
 * @author <a href="mailto:[email protected]">chenhf</a>
 * @version v1.0 <br>
 */
@Component
public class UserMedicMapper extends BaseMapper<UserMedic, Integer>{
	public UserMedic queryByNameAndPwd(UserMedic userMedic){
		return super.sqlSessionTemplate.selectOne(super.getQualifiedMethod("queryByNameAndPwd"), userMedic);
	}
}

14.UserMedic-Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chensan.mapper.sys.UserMedicMapper">
	<!-- Result Map -->
	<resultMap id="UserMedicResultMap" type="com.chensan.entity.sys.UserMedic">
		<result column="id" property="id" />
		<result column="login_name" property="loginName" />
		<result column="login_pwd" property="loginPwd" />
		<result column="user_name" property="userName" />
	</resultMap>

	<sql id="insert_Column_List">
		`login_name`,
		`login_pwd`,
		`user_name`
	</sql>

	<sql id="insert_Value_List">
		#{loginName},
		#{loginPwd},
		#{userName}
	</sql>

	<sql id="batch_Insert_Value_List">
		#{entity.loginName},
		#{entity.loginPwd},
		#{entity.userName}
	</sql>

	<sql id="update_Set_List">
		`login_name` = #{loginName},
		`login_pwd` = #{loginPwd},
		`user_name` = #{userName}
	</sql>

	<!-- 插入記錄 -->
	<insert id="insert" parameterType="com.chensan.entity.sys.UserMedic"
		useGeneratedKeys="true" keyProperty="id">
		insert into sys_user_medic(
		<include refid="insert_Column_List"></include>
		)
		values(
		<include refid="insert_Value_List"></include>
		)
	</insert>

	<!-- 批量插入記錄 -->
	<insert id="batchInsert">
		insert into sys_user_medic(
		<include refid="insert_Column_List"></include>
		)
		values
		<foreach collection="list" item="entity" separator=",">
			(
			<include refid="batch_Insert_Value_List"></include>
			)
		</foreach>
	</insert>

	<!-- 根據id,修改記錄 -->
	<update id="updateById" parameterType="com.chensan.entity.sys.UserMedic">
		update sys_user_medic set
		<include refid="update_Set_List"></include>
		where `id`=#{id}
	</update>

	<!-- 修改記錄,只修改只不爲空的字段 -->
	<update id="updateSelectiveById" parameterType="com.chensan.entity.sys.UserMedic">
		update sys_user_medic
		<set>
			<if test="loginName != null">
				`login_name` = #{loginName},
			</if>
			<if test="loginPwd != null">
				`login_pwd` = #{loginPwd},
			</if>
			<if test="Name != null">
				`user_name` = #{userName},
			</if>
		</set>
		where `id`=#{id}
	</update>

	<!-- 刪除記錄 -->
	<delete id="deleteById" parameterType="Object">
		delete from sys_user_medic
		where `id`=#{id}
	</delete>

	<!-- 批量刪除記錄 -->
	<delete id="deleteByIds" parameterType="Object">
		delete from sys_user_medic
		where `id` in
		<foreach collection="list" item="id" index="index" open="("
			close=")" separator=",">
			#{id}
		</foreach>
	</delete>

	<!-- 根據id查詢 -->
	<select id="queryById" resultMap="UserMedicResultMap"
		parameterType="Object">
		select * from sys_user_medic where
		`id`=#{id}
	</select>

	<!-- 根據id列表進行查詢 -->
	<select id="queryByIds" resultMap="UserMedicResultMap"
		parameterType="Object">
		select * from sys_user_medic where `id` in
		<foreach collection="list" item="id" index="index" open="("
			close=")" separator=",">
			#{id}
		</foreach>
	</select>

	<!-- 根據條件查詢數量 -->
	<select id="queryCount" resultType="java.lang.Long"
		parameterType="java.lang.String">
		select count(1) from sys_user_medic
		<if test="where!= null and where != ''">
			${where}
		</if>
	</select>

	<!-- 查詢所有數據 -->
	<select id="queryAll" resultMap="UserMedicResultMap">
		select * from sys_user_medic;
	</select>

	<!-- 條件分頁查詢數據 -->
	<select id="queryByPage" resultMap="UserMedicResultMap"
		parameterType="Map">
		select * from sys_user_medic
		<where>
			<if test="where!= null and where != ''">
				${where}
			</if>
		</where>

		<if test="order!= null and order != ''">
			ORDER BY ${order}
		</if>
	</select>

	<!-- 查詢條件 -->
	<sql id="Example_Where_Clause">
		where 1=1
		<trim suffixOverrides=",">
			<if test="loginName != null and loginName != ''">
				and `login_name` = #{loginName}
			</if>
			<if test="loginPwd != null and loginPwd != ''">
				and `login_pwd` = #{loginPwd}
			</if>
		</trim>
	</sql>

	<!-- 登錄查詢 -->
	<select id="queryByNameAndPwd" resultMap="UserMedicResultMap"
		parameterType="com.chensan.entity.sys.UserMedic">
		select * from sys_user_medic
		<include refid="Example_Where_Clause" />
	</select>


	<!-- 存儲過程分頁查詢數據 -->
	<select id="queryByPageAndProc" statementType="CALLABLE"
		parameterType="Map" resultMap="UserMedicResultMap">
       <![CDATA[
        	{call sys_UserMedic_queryByPage( 			
			#{startIndex,jdbcType=BIGINT},
			#{pageSize,jdbcType=BIGINT},
			
			#{loginName,jdbcType=VARCHAR},
			#{userName,jdbcType=VARCHAR},
			#{namePinyin,jdbcType=VARCHAR},
			#{belongOrganPath,jdbcType=VARCHAR},
			
			#{totalCount,mode=INOUT,jdbcType=BIGINT}
  		)}  
       ]]>
	</select>

	<!-- ******************手工新增方法放置在下面****************** -->
</mapper>
(1) IBaseService定義Entity的CRUD接口;
(2) BaseServiceImpl implements IBaseService,但是BaseServiceImpl並不操作具體的實體類;
進一步抽取公共代碼,讓Entity的ServiceImpl繼承其操作來完成Entity的CRUD;
abstract BaseMapper<T, K> getMapper(),因爲並未具體去實現,所以用abstract修飾;
(3) Entity的Service extends IBaseService<Entity entity>傳入Entity,
即對應Enity有了CRUD接口,IBaseService本就是對Entity的Service公共代碼的一個提取;
Entiy要實現IBaseService以外的數據庫操作則需要在自身的Service中擴展;
(4) Entity的ServiceImpl,拿UserMedicServiceImpl爲例,
UserMedicServiceImpl extends BaseServiceImpl<UserMedic, Integer> implements IUserMedicService
Entity的ServiceImpl extends BaseServiceImpl且傳入Entity繼承BaseServiceImpl來挖成了數據庫操作的調用;
implements的Entity的Service,則用戶可以通過簡單的調用Entity的接口來完成數據庫操作,
而不需要關心底層的實現(interface的作用);
在Entity的Service中擴展的的方法需要在Impl中去實現;
(5) Entity的Mapper是去調用Entity映射文件中的方法去實現數據庫操作的;
對於實體接口擴展和實現的操作要對應加上;
而Mapper無非也是CRUD的操作,於是有了BaseMapper這個類抽取公共的操作,
Entity的Mapper只需要傳入Entity,BaseMapper中對傳入的Entity獲取其實際路徑,
getQualifiedMethod()中獲得mybatis操作數據庫的方式namespaceName.idName;
當然getQualifiedMethod()操作轉換獲得的路徑能剛好與Entity的映射文件對應方法吻合,
依賴於包結構的設置,才能用replace替換,而Entity的路徑才能對應到某個Mapper,
Mapper中的getQualifiedMethod()中的參數對應Entity映射中的操作方法;
這樣我們調用Entity的Service就能實現數據庫的操作;
Service的接口方法,與Mapper的方法名一致,Mapper的訪法名與getQualifiedMethod()傳入參數的方法名一致,
以及Entity路徑與Entity映射文件路徑的相似
這樣的優點是:我們很簡單地從接口就可以直接找到到Entity Service在映射中的操作方法;

15. springfox + SpringMVC(分離前後臺開發)

Swagger2Config

package com.chensan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

//@Configuration
@EnableSwagger2
public class Swagger2Config {
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
			.apiInfo(apiInfo())
			.select()
			.apis(RequestHandlerSelectors.basePackage("com.chensan.api"))
			.paths(PathSelectors.any())
			.build();
	}

	private ApiInfo apiInfo() {
		Contact contact = new Contact("chenhf", "http://blog.csdn.net/qinshijangshan", "[email protected]");

		return new ApiInfoBuilder()
			.title("OAuth 2.0 RESTful APIs")
			.description("OAuth2.0 RESTFul API 文檔")
			.termsOfServiceUrl("http://blog.csdn.net/qinshijangshan")
			.license("© 2017-2025 chenhf. All rights reserved.")
			.contact(contact)
			.version("1.0")
			.build();
	}
}
在springmvc-config.xml有對swagger2的配置;

16.後臺API接口

package com.chensan.api.sys;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.chensan.common.api.ApiResponse;
import com.chensan.common.repository.ProcResult;
import com.chensan.entity.sys.UserMedic;
import com.chensan.service.sys.IUserMedicService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/sys/userMedic")
public class UserMedicRestController {
	private final static String Tags = "sys_UserMedic";

	@Autowired
	private IUserMedicService userMedicService;

	/**
	 * 創建UserMedic.
	 * 
	 * @param entity
	 *            要新增的UserMedic.
	 * @return 返回新增的UserMedic,對於自增長主鍵能夠返回插入數據庫後生成的主鍵。
	 */
	@ApiOperation(value = "創建UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "entity", value = "UserMedic實體對象", required = true, dataType = "UserMedic")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@Transactional
	public ApiResponse<UserMedic> create(@RequestBody UserMedic entity) {
		ApiResponse<UserMedic> response = new ApiResponse<UserMedic>();
		int count = 0;
		try
			{
				count = userMedicService.insert(entity);

				response.setResultCode(1);
				response.setResultMsg("新增UserMedic成功!");
				response.setData(entity);
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("新增UserMedic失敗!");
			}

		return response;
	}

	@ApiOperation(value = "批量創建UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "list", value = "UserMedic實體對象列表", required = true, dataType = "List<UserMedic>")
	@RequestMapping(value = "/create/batch", method = RequestMethod.POST)
	@Transactional
	public ApiResponse<Integer> batchCreate(@RequestBody List<UserMedic> list) {
		ApiResponse<Integer> response = new ApiResponse<Integer>();
		int count = 0;

		try
			{
				count = userMedicService.batchInsert(list);
				response.setResultCode(1);
				response.setResultMsg("批量新增UserMedic成功!");
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("批量新增UserMedic失敗!");
			}

		response.setData(count);
		return response;
	}

	@ApiOperation(value = "根據id更新UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "entity", value = "UserMedic實體對象", required = true, dataType = "UserMedic")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@Transactional
	public ApiResponse<Integer> updateById(@RequestBody UserMedic entity) {
		ApiResponse<Integer> response = new ApiResponse<Integer>();
		int count = 0;

		try
			{
				count = userMedicService.updateById(entity);
				response.setResultCode(1);
				response.setResultMsg("根據id更新UserMedic成功!");

			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("根據id更新UserMedic失敗!");
			}

		response.setData(count);
		return response;
	}

	@ApiOperation(value = "根據id部分更新UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "entity", value = "UserMedic實體對象", required = true, dataType = "UserMedic" )
	@RequestMapping(value = "/update/selective", method = RequestMethod.POST)
	@Transactional
	public ApiResponse<Integer> updateSelectiveById(@RequestBody UserMedic entity) {
		ApiResponse<Integer> response = new ApiResponse<Integer>();
		int count = 0;

		try
			{
				count = userMedicService.updateSelectiveById(entity);
				response.setResultCode(1);
				response.setResultMsg("根據id部分更新UserMedic成功!");

			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("根據id部分更新UserMedic失敗!");
			}

		response.setData(count);
		return response;
	}

	@ApiOperation(value = "根據id刪除UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "id", value = "實體對象主鍵id", required = true, dataType = "Integer", paramType="path")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.POST)
	@Transactional
	public ApiResponse<Integer> deleteById(@PathVariable Integer id) {
		ApiResponse<Integer> response = new ApiResponse<Integer>();
		int count = 0;

		try
			{
				count = userMedicService.deleteById(id);
				response.setResultCode(1);
				response.setResultMsg("根據id刪除UserMedic成功!");

			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("根據id刪除UserMedic失敗!");
			}

		response.setData(count);
		return response;
	}

	@ApiOperation(value = "根據id刪除批量UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "ids", value = "實體對象主鍵id列表(如[1,2])", required = true, dataType = "List<Integer>", paramType="body")
	@RequestMapping(value = "/del/batch/{ids}", method = RequestMethod.POST)	
	public ApiResponse<Integer> deleteByIds(@RequestBody List<Integer> ids) {
		ApiResponse<Integer> response = new ApiResponse<Integer>();
		int count = 0;

		try
			{
				count = userMedicService.deleteByIds(ids);
				response.setResultCode(1);
				response.setResultMsg("根據id批量刪除UserMedic成功!");

			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("根據id批量刪除UserMedic失敗!");
			}

		response.setData(count);
		return response;
	}

	@ApiOperation(value = "查詢指定id的UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "id", value = "實體對象主鍵id", required = true, dataType = "Integer", paramType="path")
	@RequestMapping(value = "/get/{id}", method = {
			RequestMethod.POST, RequestMethod.GET
	})
	public ApiResponse<UserMedic> queryById(@PathVariable Integer id) {
		ApiResponse<UserMedic> response = new ApiResponse<UserMedic>();

		try
			{
				UserMedic entity = userMedicService.queryById(id);
				response.setResultCode(1);
				response.setResultMsg("查詢指定id的UserMedic的成功!");
				response.setData(entity);
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("查詢指定id的UserMedic的失敗!");
			}

		return response;
	}
	
	@ApiOperation(value = "查詢指定id列表的UserMedic", notes = "", tags = Tags)
	@ApiImplicitParam(name = "ids", value = "實體對象主鍵id List", required = true, dataType = "List<Integer>", paramType = "body")
	@RequestMapping(value = "/gets", method = RequestMethod.POST)
	public ApiResponse<List<UserMedic>> queryByIds(@RequestBody List<Integer> ids) {
		ApiResponse<List<UserMedic>> response = new ApiResponse<List<UserMedic>>();

		try
			{
				List<UserMedic> entities = userMedicService.queryByIds(ids);				
				response.setResultCode(1);
				response.setResultMsg("查詢指定id的UserMedic的成功!");
				response.setData(entities);
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("查詢指定id的UserMedic的失敗!");
			}

		return response;
	}	

	@ApiOperation(value = "查詢所有的UserMedic", notes = "", tags = Tags)
	@RequestMapping(value = "/all", method = {
			RequestMethod.POST, RequestMethod.GET
	})
	public ApiResponse<List<UserMedic>> queryAll() {
		ApiResponse<List<UserMedic>> response = new ApiResponse<List<UserMedic>>();

		try
			{
				List<UserMedic> list = userMedicService.queryAll();
				response.setResultCode(1);
				response.setResultMsg("查詢所有的UserMedic的成功!");
				response.setData(list);
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("查詢所有的UserMedic的失敗!");
			}

		return response;
	}

	@ApiOperation(value = "分頁查詢UserMedic", notes = "", tags = Tags)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "startIndex", value = "實體記錄起始位置", required = true, dataType = "Long", defaultValue = "0", paramType="path"),
			@ApiImplicitParam(name = "pageSize", value = "分頁大小", required = true, dataType = "Long", defaultValue = "10", paramType="path"),
			@ApiImplicitParam(name = "totalCount", value = "記錄條數,初始查詢(或重新查詢)設爲-1", required = true, dataType = "Long", defaultValue = "-1", paramType="path"),
			@ApiImplicitParam(name = "params", value = "查詢參數", dataType = "Map<String, Object>", paramType="body")
	})
	@RequestMapping(value = "/get/page/{startIndex}/{pageSize}/{totalCount}", method = RequestMethod.POST)	
	public ApiResponse<ProcResult<UserMedic>> queryByPageAndProc(@PathVariable Long startIndex,
			@PathVariable Long pageSize, @PathVariable long totalCount, @RequestBody Map<String, Object> params) {
		ApiResponse<ProcResult<UserMedic>> response = new ApiResponse<ProcResult<UserMedic>>();

		try
			{
				ProcResult<UserMedic> result = userMedicService.queryByPageAndProc(startIndex, pageSize,
						totalCount, params);
				response.setResultCode(1);
				response.setResultMsg("分頁查詢UserMedic成功!");
				response.setData(result);
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("分頁查詢UserMedic失敗!");
			}

		return response;
	}
	
	@ApiOperation(value = "登錄", notes = "", tags = Tags)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loginName", value = "登錄名", required = true, dataType = "String", defaultValue = "", paramType="path"),
			@ApiImplicitParam(name = "password", value = "密碼", required = false, dataType = "String", defaultValue = "", paramType="path")
	})
	@RequestMapping(value = "/get/login/{loginName}", method = RequestMethod.POST)	
	public ApiResponse<UserMedic> queryByLogin(@PathVariable String loginName) {
		ApiResponse<UserMedic> response = new ApiResponse<UserMedic>();

		try
			{
				UserMedic temp = new UserMedic();
				temp.setLoginName(loginName);
//				temp.setLoginPwd(password);
			
				
				UserMedic userMedic = userMedicService.queryByNameAndPwd(temp);
				response.setResultCode(1);
				response.setResultMsg("登錄成功!");
				response.setData(userMedic);
			} catch (Exception ex)
			{
				response.setResultCode(0);
				response.setResultMsg("登錄失敗!");
			}

		return response;
	}	
}

訪問:http://localhost/bphss-test/swagger-ui.html,展示所有API的CRUD;


如果不用springfox,不進行前後端分離,那麼也就是web層代替了api層的數據庫操作,web層的業務邏輯和數據庫持久化都放在web層的Controller中進行操作;

到此後臺API操作已完成。


上一篇:SpringMVC整合Spring


發佈了102 篇原創文章 · 獲贊 49 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章