您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

IDEA+Mybatis+Mysql+Swagger 入门练习

bubuko 2022/1/25 20:05:48 mysql 字数 40497 阅读 851 来源 http://www.bubuko.com/infolist-5-1.html

用IDEA+Mybatis+Mysql+Swagger?搭建简单的增删查改接口。 开发环境:IntelliJ IDEA 2018.2.6,mysql 8.0.13 1、创建项目,搭建项目基础框架。 1.1、打开IDEA,New?Project,选择?Spring?Initializr,点击Next。 ...

 用IDEA+Mybatis+Mysql+Swagger 搭建简单的增删查改接口。

开发环境:IntelliJ IDEA 2018.2.6,mysql 8.0.13

 1、创建项目,搭建项目基础框架。

1.1、打开IDEA,New Project,选择 Spring Initializr,点击Next。

技术分享图片

 

 

1.2、填写项目名称,选择Java版本。点击Next。

技术分享图片

 

 

1.3、选择Spring Web,JDBC API,MyBatis Framewrok,MySql Driver。点击Next。

技术分享图片

 

技术分享图片

 

1.4、填写项目名称,保存地址。点击Finish。

技术分享图片

 

1.5、开发前先修改Maven远程仓库地址。由于Maven默认的远程仓库是外国服务器,加载需要的包会比较慢,我们改为国内的阿里云仓库地址。

左上角File->Settings。选择Build,Execution,Deployment。选择已安装的Maven,打开Settings.xml,找到mirrors标签将原来的仓库地址改为阿里云的:http://maven.aliyun.com/nexus/content/groups/public/ 。

技术分享图片

 

技术分享图片

 

技术分享图片

 

 1.6、项目加载完成后初始框架目录如下。修改pom.xml文件,手工引入了alibaba德鲁伊数据源连接池druid、jackson-core、jackson-databind、pagehelper,swagger等依赖.

技术分享图片

 

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>testdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testdemo</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- alibaba德鲁伊数据源连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>

<!--分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

2、建表,添加数据库配置。
2.1 建两张表:dept、userinfo

CREATE TABLE `dept` (
`dept_no` int(11) NOT NULL,
`dept_name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`dept_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

 

CREATE TABLE `userinfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_account` varchar(30) DEFAULT NULL,
`password` varchar(20) NOT NULL,
`nick_name` varchar(50) NOT NULL,
`dept_no` int(11) NOT NULL DEFAULT ‘1001‘,
`phone_num` bigint(20) NOT NULL,
`email_address` varchar(50) NOT NULL,
`birth_day` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

 

2.2 添加数据库访问账号

--创建用户
create user ‘robbot‘@‘%‘ identified by ‘robbot123‘;
--授权
grant all privileges on test.* to robbot@‘%‘;
--刷新
flush privileges;

2.3  配置数据访问连接:删除resources文件夹下的application.properties文件改成格式简单的application.yml文件。具体配置如下:

server:
port: 8090

spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: robbot
password: robbot123
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select ‘x‘
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20

## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
mapper-locations: classpath:com.example.demo.dao/*.xml #注意:一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.example.demo.model # 注意:对应实体类的路径

#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql


3、接口开发
3.1 搭建4层框架:controller,service,business,mapper。结构如下:
技术分享图片

 

 

 3.2  model 类代码:UserTo 类

package com.example.testdemo.model;
import java.io.Serializable;

public class UserTO implements Serializable {
private int id;
private int dept_no;
private String dept_name;
private String user_account;
private String password;
private String nick_name;
private String email_address;
private String birth_day;
private Long phone_num;

public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public int getDeptNo(){
return dept_no;
}
public void setDeptNo(int deptNo){
this.dept_no=deptNo;
}
public String getDeptName(){
return dept_name;
}
public void setDeptName(String deptName){
this.dept_name=deptName;
}
public String getUserAccount() {
return user_account;
}
public void setUserAccount(String userAccount) {
this.user_account = userAccount;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nick_name;
}
public void setNickName(String nickName) {
this.nick_name = nickName;
}
public String getEmailAddress() {
return email_address;
}
public void setEmailAddress(String emailAddress) {
this.email_address = emailAddress;
}
public String getBirthDay() {
return birth_day;
}
public void setBirthDay(String birthDay) {
this.birth_day = birthDay;
}
public Long getPhoneNum() {
return phone_num;
}
public void setPhoneNum(Long phoneNum) {
this.phone_num = phoneNum;
}
}


PageInfo类
package com.example.testdemo.model;
import java.io.Serializable;
import java.util.List;

public class PageInfo<T> implements Serializable{
int pageNum;
int pageSize;
int startIndex;
int endIndex;
int totalRows;
List<T> dataList;

public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getEndIndex() {
return endIndex;
}
public void setEndIndex(int endIndex) {
this.endIndex = endIndex;
}
public List<T> getDataList() {
return dataList;
}
public void setDataList(List<T> dataList) {
this.dataList = dataList;
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
}


ServiceResponse 类
package com.example.testdemo.model;
import java.io.Serializable;

public class ServiceResponse<T> implements Serializable {
private int status;
private String message;
private String serviceId;
private T data;

public int getStatus(){
return status;
}
public void setStatus(int stauts){
this.status=stauts;
}
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message=message;
}
public String getServiceId(){
return serviceId;
}
public void setServiceId(String serviceId){
this.serviceId=serviceId;
}
public T getData(){
return data;
}
public void setData(T data){
this.data=data;
}
}

3.3 mapper接口及对应的mapper xml文件,放sql语句

IUserMapper.xml文件(注意 namespace要与IUserMapper接口的一致)
<?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.example.testdemo.mapper.IUserMapper">
<select id="queryUsersByAccount" parameterType="java.lang.String" resultType="com.example.testdemo.model.UserTO">
select u.id,u.user_account,u.password,u.nick_name,u.dept_no,d.dept_name,
u.phone_num,u.email_address,u.birth_day
from userinfo u
left join dept d on d.dept_no=u.dept_no
where u.user_account=#{userAccount,jdbcType=VARCHAR}
</select>
<select id="selectAllUser" resultType="com.example.testdemo.model.UserTO">
select a.id,a.user_account,a.password,a.nick_name,
a.dept_no,a.phone_num,a.email_address,a.birth_day
from userinfo a
where a.id>=#{startIndex,jdbcType=INTEGER} limit #{pageSize,jdbcType=INTEGER}
</select>
<select id="queryTotalRows" resultType="int">
select count(1) from ${dbName}
</select>
<insert id="addUserInfo" parameterType="com.example.testdemo.model.UserTO">
insert into userinfo
(user_account,
password,
phone_num,
dept_no,
birth_day,
nick_name,
email_address
)
values(
#{userAccount,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{phoneNum,jdbcType=NUMERIC},
#{deptNo,jdbcType=NUMERIC},
#{birthDay,jdbcType=VARCHAR},
#{nickName,jdbcType=VARCHAR},
#{emailAddress,jdbcType=VARCHAR}
)
</insert>
<insert id="batchAddUserInfo" parameterType="java.util.List">
insert into userinfo(
user_account,
password,
phone_num,
dept_no,
birth_day,
nick_name,
email_address
)
<foreach collection="list" item="item" index="index" separator="union all">
select
#{item.userAccount,jdbcType=VARCHAR},
#{item.password,jdbcType=VARCHAR},
#{item.phoneNum,jdbcType=NUMERIC},
#{item.deptNo,jdbcType=NUMERIC},
#{item.birthDay,jdbcType=VARCHAR},
#{item.nickName,jdbcType=VARCHAR},
#{item.emailAddress,jdbcType=VARCHAR}
from dual
</foreach>
</insert>
<update id="updateUserInfo" parameterType="com.example.testdemo.model.UserTO">
update userinfo
<trim prefix="set" suffixOverrides=",">
<if test="password!=null and password!=‘‘ ">password=#{password,jdbcType=VARCHAR},</if>
<if test="phoneNum!=null ">phoneNum=#{phoneNum,jdbcType=NUMERIC},</if>
<if test="deptNo!=null">deptNo=#{deptNo,jdbcType=NUMERIC},</if>
<if test="birthDay!=null">birthDay=#{birthDay,jdbcType=VARCHAR},</if>
<if test="nickName!=null and nickName!=‘‘ ">nickName=#{nickName,jdbcType=VARCHAR},</if>
<if test="emailAddress!=null and emailAddress!=‘‘ ">emailAddress=#{emailAddress,jdbcType=VARCHAR}</if>
</trim>
where user_account=#{userAccount,jdbcType=VARCHAR}
</update>

<update id="batchUpdateUserInfo" parameterType="java.util.List">
<foreach collection="list" separator=";" item="item" close=";">
update userinfo
<trim prefix="set" suffixOverrides=",">
<if test="password!=null and password!=‘‘ ">password=#{password,jdbcType=VARCHAR},</if>
<if test="phoneNum!=null ">phoneNum=#{phoneNum,jdbcType=NUMERIC},</if>
<if test="deptNo!=null">deptNo=#{deptNo,jdbcType=NUMERIC},</if>
<if test="birthDay!=null">birthDay=#{birthDay,jdbcType=VARCHAR},</if>
<if test="nickName!=null and nickName!=‘‘ ">nickName=#{nickName,jdbcType=VARCHAR},</if>
<if test="emailAddress!=null and emailAddress!=‘‘ ">emailAddress=#{emailAddress,jdbcType=VARCHAR}</if>
</trim>
where user_account=#{item.userAccount,jdbcType=VARCHAR}
</foreach>
</update>
<delete id="deleteUserInfo" parameterType="java.lang.String">
delete from userinfo where user_account=#{param1,jdbcType=VARCHAR}
</delete>

<delete id="batchDeleteUserInfo" parameterType="java.util.List">
delete from userinfo where user_accont in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item,jdbcType=VARCHAR}
</foreach>
</delete>
</mapper>

IUserMapper接口
package com.example.testdemo.mapper;
import com.example.testdemo.model.UserTO;
import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface IUserMapper {
UserTO queryUsersByAccount(@Param("userAccount")String userAccount);
List<UserTO> selectAllUser(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);
void addUserInfo(UserTO userTo);
void updateUserInfo(UserTO userTo);
void batchAddUserInfo(List<UserTO> userItems);
int queryTotalRows(@Param("dbName") String dbName);
void batchUpdateUserInfo(List<UserTO> userItems);
void deleteUserInfo(String userAccount);
void batchDeleteUserInfo(List<String> userAccounts);
}

3.5 business 接口及类
IUserBusiness接口
package com.example.testdemo.business;

import com.example.testdemo.model.UserTO;

import java.util.List;

public interface IUserBusiness {
UserTO queryUsersByAccount(String userAccount);
void addUserInfo(UserTO userTo) throws Exception;
void updateUserInfo(UserTO userTo) throws Exception ;
void batchInsertUserInfo(List<UserTO> items)throws Exception;
List<UserTO> selectAllUser(int startIndex,int pageSize);
int queryTotalRows(String dbName);
void batchUpdateUserInfo(List<UserTO> item) throws Exception;
void deleteUserInfo(String userAccount)throws Exception;
void batchDeleteUserInfo(List<String> userAccounts)throws Exception;
}

UserBusiness类

package com.example.testdemo.business.impl;

import com.example.testdemo.business.IUserBusiness;
import com.example.testdemo.mapper.IUserMapper;
import com.example.testdemo.model.UserTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Component
public class UserBusiness implements IUserBusiness {
@Autowired
private IUserMapper userMapper;

@Override
public UserTO queryUsersByAccount(String userAccount) {
return userMapper.queryUsersByAccount(userAccount);
}

@Override
@Transactional(rollbackFor = {Exception.class},readOnly=false)
public void addUserInfo(UserTO userTo)throws Exception {
userMapper.addUserInfo(userTo);
}

@Override
@Transactional(rollbackFor = {Exception.class},readOnly = false)
public void updateUserInfo(UserTO userTo) throws Exception {
userMapper.updateUserInfo(userTo);
}

@Override
@Transactional(rollbackFor={Exception.class},readOnly = false)
public void batchInsertUserInfo(List<UserTO> items) throws Exception {
userMapper.batchAddUserInfo(items);
}

@Override
public List<UserTO> selectAllUser(int startIndex, int pageSize) {
//将分页参数传给PageHelper类的startPage(int pageNum,int pageSize)静态方法即可实现分页效果,非常简单
return userMapper.selectAllUser(startIndex,pageSize);
}

@Override
public int queryTotalRows(String dbName) {
return userMapper.queryTotalRows(dbName);
}

@Override
@Transactional(rollbackFor = {Exception.class},readOnly = false)
public void batchUpdateUserInfo(List<UserTO> item) throws Exception {
userMapper.batchUpdateUserInfo(item);
}

@Override
@Transactional(rollbackFor = {Exception.class},readOnly = false)
public void deleteUserInfo(String userAccount) throws Exception {
userMapper.deleteUserInfo(userAccount);
}

@Override
@Transactional(rollbackFor = {Exception.class},readOnly = false)
public void batchDeleteUserInfo(List<String> userAccounts) throws Exception {
userMapper.batchDeleteUserInfo(userAccounts);
}
}
 


3.6 service接口及类

IUserService接口
package com.example.testdemo.service;
import com.example.testdemo.model.PageInfo;
import com.example.testdemo.model.ServiceResponse;
import com.example.testdemo.model.UserTO;
import java.util.List;

public interface IUserService {
ServiceResponse<UserTO> queryUserInfoByAccount(String userAccount);

ServiceResponse<String> addUserTO(UserTO userTO);

ServiceResponse<String> updateUserTO(UserTO userTO);

ServiceResponse<String> batchAddUserTO(List<UserTO> userTOs);

ServiceResponse<PageInfo> selectAllUser(int pageNum, int pageSize);

ServiceResponse<String> batchUpdateUserInfo(List<UserTO> userItems);

ServiceResponse<String> deleteUserInfo(String userAccount);

ServiceResponse<String> batchDeleteUserInfo(List<String> userAccounts);
}

UserService类
package com.example.testdemo.service.impl;

import com.example.testdemo.business.IUserBusiness;
import com.example.testdemo.model.PageInfo;
import com.example.testdemo.model.ServiceResponse;
import com.example.testdemo.model.UserTO;
import com.example.testdemo.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {
@Autowired
private IUserBusiness userBusiness;

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

@Override
public ServiceResponse<UserTO> queryUserInfoByAccount(String userAccount) {
ServiceResponse<UserTO> response=new ServiceResponse<>();
UserTO userTO=userBusiness.queryUsersByAccount(userAccount);
response.setStatus(200);
response.setMessage("ok");
response.setData(userTO);
return response;
}

@Override
public ServiceResponse<String> addUserTO(UserTO userTO) {
ServiceResponse<String> response=new ServiceResponse<>();
try {
userBusiness.addUserInfo(userTO);
response.setStatus(200);
response.setMessage("ok");
response.setData("success");
} catch (Exception e) {
response.setMessage("inner service error:"+e.getMessage());
response.setStatus(500);
response.setData("error");
logger.error(e.getMessage(),e);
}
return response;
}

@Override
public ServiceResponse<String> updateUserTO(UserTO userTO) {
ServiceResponse<String> response=new ServiceResponse<>();
try {
userBusiness.updateUserInfo(userTO);
response.setStatus(200);
response.setMessage("ok");
response.setData("success");
} catch (Exception e) {
response.setMessage("inner service error:"+e.getMessage());
response.setStatus(500);
response.setData("error");
logger.error(e.getMessage(),e);
}
return response;

}

@Override
public ServiceResponse<String> batchAddUserTO(List<UserTO> userTOs) {
ServiceResponse<String> response=new ServiceResponse<>();
try {
userBusiness.batchInsertUserInfo(userTOs);
response.setStatus(200);
response.setMessage("ok");
response.setData("success");
} catch (Exception e) {
response.setMessage("inner service error:"+e.getMessage());
response.setStatus(500);
response.setData("error");
logger.error(e.getMessage(),e);
}
return response;

}

@Override
public ServiceResponse<PageInfo> selectAllUser(int pageNum, int pageSize) {
ServiceResponse<PageInfo> response=new ServiceResponse<>();
PageInfo pageInfo=new PageInfo();
pageInfo.setPageNum(pageNum);
pageInfo.setPageSize(pageSize);
int startIndex=(pageNum-1)*pageSize+1;
int endIndex=pageNum*pageSize;
pageInfo.setStartIndex(startIndex);
int totalRows=userBusiness.queryTotalRows("userinfo");
if (totalRows<endIndex){
endIndex=totalRows;
}
pageInfo.setEndIndex(endIndex);
pageInfo.setTotalRows(totalRows);
List<UserTO> resultList=userBusiness.selectAllUser(startIndex,pageSize-1);
pageInfo.setDataList(resultList);
response.setStatus(200);
response.setMessage("ok");
response.setData(pageInfo);
return response;
}

@Override
public ServiceResponse<String> batchUpdateUserInfo(List<UserTO> userItems) {
ServiceResponse<String> response = new ServiceResponse<>();
try{
userBusiness.batchUpdateUserInfo(userItems);
response.setStatus(200);
response.setMessage("ok");
response.setData("success!");
}catch(Exception ex){
response.setStatus(500);
response.setMessage("inner service error:"+ex.getMessage());
response.setData("error");
logger.error(ex.getMessage(),ex);

}
return response;
}

@Override
public ServiceResponse<String> deleteUserInfo(String userAccount) {
ServiceResponse<String> response = new ServiceResponse<>();
try{
userBusiness.deleteUserInfo(userAccount);
response.setStatus(200);
response.setMessage("ok");
response.setData("success!");
}catch(Exception ex){
response.setStatus(500);
response.setMessage("inner service error:"+ex.getMessage());
response.setData("error");
logger.error(ex.getMessage(),ex);
}
return response;
}

@Override
public ServiceResponse<String> batchDeleteUserInfo(List<String> userAccounts) {
ServiceResponse<String> response = new ServiceResponse<>();
try{
userBusiness.batchDeleteUserInfo(userAccounts);
response.setStatus(200);
response.setMessage("ok");
response.setData("success!");
}catch(Exception ex){
response.setStatus(500);
response.setMessage("inner service error:"+ex.getMessage());
response.setData("error");
logger.error(ex.getMessage(),ex);
}
return response;
}
}

3.7 Controller类
package com.example.testdemo.controller;
import com.example.testdemo.model.PageInfo;
import com.example.testdemo.model.ServiceResponse;
import com.example.testdemo.model.UserTO;
import com.example.testdemo.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value="/user")
@Api(value = "MybatisController|一个用来测试swagger注解的控制器")
public class MybatisController {
@Autowired
private IUserService userService;

@RequestMapping(value= "/userinfo",method = RequestMethod.GET)
@ApiOperation(value = "根据账号查看用户信息", httpMethod = "GET")
public ServiceResponse<UserTO> getUserInfoByAccount(@RequestParam("uesrAccount") String userAccount){
return userService.queryUserInfoByAccount(userAccount);
}

/**
* 添加单个用户信息
* @param userTO
* @return
*/
@RequestMapping(value="add/userinfo",method=RequestMethod.POST)
public ServiceResponse<String> addUserInfo(@RequestBody UserTO userTO){

return userService.addUserTO(userTO);
}

/**
* 修改单个用户信息
* @param userTO
* @return
*/
@RequestMapping(value="/update/userinfo",method = RequestMethod.POST)
public ServiceResponse<String> updateUserInfo(@RequestBody UserTO userTO){

return userService.updateUserTO(userTO);
}

/**
* 批量添加用户信息
* @param userTOs
* @return
*/
@RequestMapping(value="/batchadd/userinfo",method=RequestMethod.POST)
public ServiceResponse<String> batchAddUserInfo(@RequestBody List<UserTO> userTOs){

return userService.batchAddUserTO(userTOs);
}

/**
* 分页查询用户信息
* @param pageNum
* @param pageSize
* @return
*/
@RequestMapping(value="alluser/page",method=RequestMethod.GET)
public ServiceResponse<PageInfo> queryAllUser(@RequestParam(value="pageNum") int pageNum,
@RequestParam(value="pageSize") int pageSize){
return userService.selectAllUser(pageNum,pageSize);
}

/**
* 批量修改用户信息
* @param userItems
* @return
*/
@RequestMapping(value="/batch/update",method = RequestMethod.POST)
public ServiceResponse<String> batchUpdateUserInfo(@RequestBody List<UserTO> userItems){

return userService.batchAddUserTO(userItems);
}

/**
* 根据用户名删除单个用户信息
* @param userAccount
* @return
*/
@RequestMapping(value="/delete/userinfo",method=RequestMethod.DELETE)
public ServiceResponse<String> deleteUserInfo(@RequestParam("userAccount") String userAccount){
return userService.deleteUserInfo(userAccount);
}

/**
* 批量删除用户信息
* @param userAccounts
* @return
*/
@RequestMapping(value="/delete/batch",method = RequestMethod.POST)
public ServiceResponse<String> batchDeleteUserInfo(@RequestBody List<String> userAccounts){

return userService.batchDeleteUserInfo(userAccounts);
}
}

4.配置Application启动类
在TestdemoApplication类添加添加@MapperScan注解,basePackages为mapper的命名空间。此时该项目已搭建完成,可启动项目,打开浏览器或Postman调用接口测试。
技术分享图片

 

 

5.配置Swagger

 

在Application的同级目录下添加Swagger2类

 

package com.example.testdemo;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class Swagger2 {

/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.testdemo.controller"))
.paths(PathSelectors.any())
.build();
}

/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多请关注http://www.baidu.com")
.termsOfServiceUrl("http://www.baidu.com")
.contact("sunf")
.version("1.0")
.build();
}
}

此处修改为controller的命名空间

技术分享图片

 

 

此时Swagger搭建完成,启动项目,在浏览器中输入 localhost:端口号/swagger-ui.html 可以测试接口。

 技术分享图片

 

ref:https://blog.csdn.net/heshengfu1211/article/details/85490612 

     https://blog.csdn.net/sanyaoxu_2/article/details/80555328

 



 

 

 

IDEA+Mybatis+Mysql+Swagger 入门练习

原文:https://www.cnblogs.com/greennnnnnnn/p/12484586.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶