一.本篇主要讲解内容
主要讲解从如何创建一个项目到通过swagger对mysql中的数据进行增删查改操作。
二.构建步骤
1.创建项目
2.配置文件
3.引入依赖
4.配置swagger
5.编写entity实体、mapping类以及mapping对应的xml文件
6.编写service调用mapping
7.编写controller调用service方法
三.具体步骤
1.创建项目
选择spring initializr 以及 java 8 后(项目名称这些根据自己设置)点击next、 之后选择 Lombok 、Spring Web 、Thymeleaf 、MyBatis Framework
点击完成,项目就创建成功了。
2.配置文件
首先项目创建完成之后目录是这样的,在application.properties中加入连接数据库以及之后会用的一些配置信息、
spring.datasource.url=jdbc:mysql://192.168.1.129:3306/test2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'
spring.datasource.username=admin
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql:
# mybatis的 Mapping.xml的位置
mybatis.mapper-locations=classpath:mapping
3引入依赖
<!--swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--Spring JDBC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<!--Mybatis starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--mybatis分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.1</version>
</dependency>
<!--分页插件springbootstarter-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<!--mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!--druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
4.配置swagger 如图所示位置创建四个包(controller,entity,mapper,service)和一个swagger类。之后写入swagger的配置信息。 swagger中的配置代码
package com.example.mybatisdome;
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 swagger {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.mybatisdome.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("电竞杜兰特测试Swagger项目")
.description("接口的说明")
.contact("lcl")
.version("1.0.0")
.build();
}
}
5.编写entity实体、mapping类以及mapping对应的xml文件
1.根据数据库的表,在entity下创建一个User实体 2.在mapper包下创建一个UserMapper(注意UserMapper类型)写入增删查改四个方法
package com.example.mybatisdome.mapper;
import com.example.mybatisdome.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserMapper {
public List<User> listAllUser();
public void delUserById(@Param("id") int id);
public int addUser(User user);
public void updateUser(User user);
public List<User> findUserByName(@Param("name") String name,@Param("use_state") Integer use_state );
public List<User> findUserByDepatrtment(@Param("departmentid") Integer departmentid );
}
3.在这个位置创建一个mapping包在该包下创建一个对应的UserMapping.xml文件,在UserMapping.xml文件中写入对应的sql语句。 注意:因为application.properties中配置只扫描*Mapping.xml所以自己创建的xml文件后缀必须为Mapping。 类似于这样的路径名记得改为自己项目中相对于的。(“com.example.mybatisdome.mapper.UserMapper” , com.example.mybatisdome.entity.User)
<?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">
<!--namespace:命名空间,是用于绑定Dao接口的,即面向接口编程,必须写为被绑定接口的全类名-->
<mapper namespace="com.example.mybatisdome.mapper.UserMapper">
<resultMap id="UserResultMap" type="com.example.mybatisdome.entity.User">
<!--id 中的column 必须是主键字段-->
<!--
column : 表的字段,或者可以为查询语句中的别名字段
jdbcType : 字段类型
property : 映射pojo对象的主键属性"
-->
<!-- private int id;-->
<!-- private String name;-->
<!-- private String log_name;-->
<!-- private String password;-->
<!-- private String sex;-->
<!-- private int use_state;-->
<!-- private String address;-->
<!-- private int departmentid;-->
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="log_name" jdbcType="VARCHAR" property="log_name" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="sex" jdbcType="VARCHAR" property="sex"/>
<result column="use_state" jdbcType="INTEGER" property="use_state"/>
<result column="address" jdbcType="VARCHAR" property="address"/>
<result column="departmentid" jdbcType="INTEGER" property="departmentid"/>
</resultMap>
<select id="listAllUser" resultType="com.example.mybatisdome.entity.User">
select id,name,log_name,password,sex,use_state,address,departmentid from user
</select>
<delete id="delUserById" parameterType="int">
delete from user where id = #{id}
</delete>
<insert id="addUser" parameterType="com.example.mybatisdome.entity.User" keyColumn="id" useGeneratedKeys="true">
insert into user (id,name,log_name,password,sex,use_state,address,departmentid) values(#{id},#{name},#{log_name},#{password},#{sex},#{use_state},#{address},#{departmentid})
</insert>
<update id="updateUser" parameterType="com.example.mybatisdome.entity.User">
update user set name = #{name},log_name = #{log_name},password = #{password},sex=#{sex},use_state=#{use_state},address=#{address},departmentid=#{departmentid} where id = #{id}
</update>
<select id="findUserByName" resultMap="UserResultMap">
select * from user
<!-- 方式一: 使用where标签 -->
<where>
<if test="name != null and name != '' ">
and name like "%"#{name,jdbcType=VARCHAR}"%"
</if>
<if test="use_state != null">
and use_state = #{use_state,jdbcType=INTEGER}
</if>
</where>
</select>
<select id="findUserByDepatrtment" resultType="com.example.mybatisdome.entity.User">
select id,name,log_name,password,sex,use_state,address,departmentid from user where departmentid = #{departmentid,jdbcType=INTEGER}
</select>
</mapper>
6.编写service调用mapping
在service包下创建一个UserService类,并在其中写于函数调用mapper中的函数。
package com.example.mybatisdome.service;
import com.example.mybatisdome.entity.User;
import com.example.mybatisdome.mapper.UserMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserService {
@Resource
private UserMapper userMapper;
public List<User> listAllUser(){
return userMapper.listAllUser();
}
public void delUserById(@Param("id") int id){
userMapper.delUserById(id);
}
public int addUser(User user){
return userMapper.addUser(user);
}
public void updateUser(User user){
userMapper.updateUser(user);
}
public Map<String,Object> findUserByName(@Param("name") String name,@Param("use_state") Integer use_state ){
List<User> lists=userMapper.findUserByName(name,use_state);
Map<String,Object> map = new HashMap<>();
map.put("data",lists);
return map;
}
public Map<String,Object> findUserByDepatrtment(@Param("departmentid") Integer departmentid ){
List<User> lists=userMapper.findUserByDepatrtment(departmentid);
Map<String,Object> map = new HashMap<>();
map.put("data",lists);
return map;
}
}
7.编写controller调用service方法
在controller层中创建一个UserController类,写入Api接口再调用service层函数。
package com.example.mybatisdome.controller;
import com.example.mybatisdome.entity.User;
import com.example.mybatisdome.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@Slf4j
@RequestMapping(value = "/user")
@Api(value = "用户接口", tags = "用户的接口" )
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
@ApiOperation(value = "新增用户信息", notes = "新增用户信息")
public boolean addUser( User user) {
log.info("开始新增...{}",user);
userService.addUser(user);
return true;
}
@RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
@ApiOperation(value = "更新用户信息", notes = "更新用户信息")
public boolean updateUser( User user) {
log.info("开始更新...{}",user);
userService.updateUser(user);
return true;
}
@RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE)
@ApiOperation(value = "删除用户信息", notes = "删除用户信息")
public boolean delete(@RequestParam(value = "userId", required = true) int userId) {
log.info("开始删除...userId={}",userId);
userService.delUserById(userId);
return true;
}
@RequestMapping(value = "/userAll", method = RequestMethod.GET)
@ApiOperation(value = "查询所有用户信息", notes = "查询所有用户信息")
public List<User> findByUserAge() {
log.info("开始查询所有数据...");
return userService.listAllUser();
}
@RequestMapping(value = "/findbyname", method = RequestMethod.GET)
@ApiOperation(value = "通过姓名和状态查询用户信息", notes = "通过姓名和状态查询用户信息")
public Map<String,Object> findUserByName(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "use_state", required = true) Integer use_state ) {
Map<String,Object> info = userService.findUserByName(name,use_state);
return info;
}
@RequestMapping(value = "/findbydepartment", method = RequestMethod.GET)
@ApiOperation(value = "通过部门编号查询用户信息", notes = "通过部门编号查询用户信息")
public Map<String,Object> findUserByDepartment(@RequestParam(value = "departmentid", required = true) Integer departmentid ) {
Map<String,Object> info = userService.findUserByDepatrtment(departmentid);
return info;
}
}
结果演示
由于操作比较慢演示的时候只是随便测试了几个接口,演示就是最上面的gif动图。
|