springboot+mybatis+swagger实现的Demo

Posted wangxiaochao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot+mybatis+swagger实现的Demo相关的知识,希望对你有一定的参考价值。

项目描述:最近入职的公司使用的springboot构建项目,由于以前学习的传统的ssm框架,而且没有运用到实际中去。在此通过这个项目来熟悉整个流程。

此项目是一个比较简单的项目,主要是对用户增删改查的功能,分页功能也没有加入。

整个项目分包结构:entity实例包,dto包、dto.map、config、mapper、service、controller

解释:本例中用的是User实例,对应的是UserDTO,UserDTO方便于传输数据,数据以json格式传输。

1.UserDtoMap用于实体类和DTO类的转化,前端通过传入json格式的数据,controller中通过DTO类去接收,然后转化为对应的实体类,实体类和数据库之间进行操作。后端向前端返回String类型的数据或者DTO类型的数据。

2.config中的是一个swagger的配置类,mapper中是一个UserMapper.java的接口,此接口中定义了一些对User对象的增删改查,对应的是resources下的mapper,也就是UserMaper.xml文件,定义了对应的SQL语句,实现UserMapper.java接口。

具体的代码如下:

config包下

package com.example.learndemo.controller;

import com.example.learndemo.dto.UserDTO;
import com.example.learndemo.dto.map.UserDtoMap;
import com.example.learndemo.entity.User;
import com.example.learndemo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@Api(tags = "1.1、用户管理接口")
@RequestMapping("/v1/userMg")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 查询所有用户,未加入分页功能
     */
    @ApiOperation(value = "获取所有用户信息")
    @GetMapping
    public List<UserDTO> getAll(){
        List<User> userList = userService.findAll();
        List<UserDTO> userDTOList = UserDtoMap.MAP.to(userList);
        return userDTOList;
    }

    /**
     * 添加用户
     */
    @ApiOperation(value = "添加用户")
    @PostMapping
    public String insert(@Valid @RequestBody UserDTO userDTO){
        //转换数据
        User user = UserDtoMap.MAP.from(userDTO);
        //插入数据
        int result = userService.insertOne(user);
        //根据插入的结果返回对应的请求结果
        return result>0 ? "SUCCESS" : "error";
    }

    /**
     * 删除用户
     */
    @ApiOperation(value = "删除用户")
    @DeleteMapping(value = "/{id}")
    public String delete(@PathVariable(value = "id") Long id){

        int result = userService.deleteOne(id);

        return result>0 ? "SUCCESS" : "error";
    }

    /**
     * 更新用户,根据id去更新
     */
    @ApiOperation(value = "更新用户信息")
    @PutMapping(value = "/{id}")
    public String update(@ApiParam(value = "主键id",required = true) @PathVariable(value = "id") Long id,
                         @RequestBody UserDTO userDTO){
        User user = userService.findById(id);
        //断言该对象不为空,如果为空,抛出message信息
        Assert.notNull(user,"该数据不存在");
        user = UserDtoMap.MAP.from(userDTO);
        user.setId(id);
        int result = userService.update(user);
        return result>0 ? "SUCCESS" : "error";
    }

}

entity包下

package com.example.learndemo.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class User implements Serializable {
    /**
     * 主键id
     */
    private Long id;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 密码
     */
    private String password;

    private static final long serialVersionUID = 1L;

}

建表sql

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 主键id,
  `user_name` varchar(20) DEFAULT NULL COMMENT 用户名,
  `password` varchar(32) DEFAULT NULL COMMENT 密码,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8 COMMENT=用户管理;

dto包下

package com.example.learndemo.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
@ApiModel(value = "UserDTO", description = "用户管理的DTO")
public class UserDTO implements Serializable {
    /**
     * 主键id
     */
    @JSONField(serializeUsing = ToStringSerializer.class)
    @ApiModelProperty(value="主键id")
    private Long id;

    /**
     * 用户名
     */
    @ApiModelProperty(value="用户名")
    private String userName;

    /**
     * 密码
     */
    @ApiModelProperty(value="密码")
    private String password;

    private static final long serialVersionUID = 1L;

}

dto.map包下

package com.example.learndemo.dto.map;

import java.util.List;
import org.mapstruct.InheritConfiguration;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mappings;

public interface BasicMapper<SOURCE, TARGET> {
    @Mappings({})
    @InheritConfiguration
    TARGET to(SOURCE var1);

    @InheritConfiguration
    List<TARGET> to(List<SOURCE> var1);

    @InheritInverseConfiguration
    SOURCE from(TARGET var1);

    @InheritInverseConfiguration
    List<SOURCE> from(List<TARGET> var1);
}
package com.example.learndemo.dto.map;

import com.example.learndemo.dto.UserDTO;
import com.example.learndemo.entity.User;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserDtoMap extends BasicMapper<User, UserDTO>{
    /**
     * 获取Mapper
     */
    UserDtoMap MAP = Mappers.getMapper(UserDtoMap.class );
}

mapper包下:

package com.example.learndemo.mapper;

import com.example.learndemo.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {

    int insertOne(User user);

    int update(User user);

    int deleteOne(Long id);

    User findById(Long id);

    List<User> findAll();
}

service包下:

package com.example.learndemo.service;

import com.example.learndemo.entity.User;

import java.util.List;

public interface UserService {

    int insertOne(User user);

    int update(User user);

    int deleteOne(Long id);

    User findById(Long id);

    List<User> findAll();
}

service实现类:

package com.example.learndemo.service.impl;

import com.example.learndemo.entity.User;
import com.example.learndemo.mapper.UserMapper;
import com.example.learndemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wxc
 */
@Service
public class UserServiceImpl implements UserService {


    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public int insertOne(User user) {
        return userMapper.insertOne(user);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public int deleteOne(Long id) {
        return userMapper.deleteOne(id);
    }

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
}

启动类:

package com.example.learndemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
//@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan
//@EnableConfigurationProperties(ReadProperties.class)
@MapperScan("com.example.learndemo.mapper")
@SpringBootApplication
@ServletComponentScan
@EnableSwagger2
public class LearnDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(LearnDemoApplication.class, args);
    }
}

resources目录下mapper包下:

<?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.learndemo.mapper.UserMapper">

    <insert id="insertOne" parameterType="com.example.learndemo.entity.User">
        insert into user(user_name,password) values(#{userName}, #{password})
    </insert>

   <update id="update" parameterType="com.example.learndemo.entity.User">
           update user set user_name=#{userName},password=#{password} WHERE id=#{id}
   </update>

    <delete id="deleteOne" parameterType="long">
          delete from user where id=#{_parameter}
   </delete>

    <select id="findById" parameterType="long" resultType="com.example.learndemo.entity.User">
        select id,user_name userName,password from user where id=#{_parameter}
    </select>

    <select id="findAll" resultType="com.example.learndemo.entity.User">
        select id,user_name userName,password from user
    </select>
</mapper>

application.yml文件:

spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/learndb
    username: root
    password: root

# mybatis的Mapper是他扫描
mybatis:
#  type-aliases-package: com.yuanmao.certs.apps.domain.entity
  mapper-locations: classpath:mapper/*.xml

application-dev.yml文件:

server:
  port: 8081

访问http://127.0.0.1:8081/swagger-ui.html最终效果:

技术分享图片

技术分享图片

 

以上是关于springboot+mybatis+swagger实现的Demo的主要内容,如果未能解决你的问题,请参考以下文章

Springboot2.x最全整合系列(持续更新)

后端学习路线(持续更新中...)

SpringBoot使用·下篇(SpringBoot集成MyBatis+日志打印+MyBatis-plus)

SpringBoot使用·下篇(SpringBoot集成MyBatis+日志打印+MyBatis-plus)

SpringBoot 整合其他框架 -- SpringBoot整合Mybatis

springboot.springboot用最简单的方式整合mybatis