idea工具+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最終效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM