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:1619427973@qq.com">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:1619427973@qq.com">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:1619427973@qq.com">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:1619427973@qq.com">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:1619427973@qq.com">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", "1619427973@qq.com");
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操作已完成。