spring boot+swagger实现数据库增删查改

IDEA+spring boot+maven+mysql+swagger+rest风格
首先准备数据库:

CREATE DATABASE `demo`;
USE `demo`;
DROP TABLE IF EXISTS `message`;

CREATE TABLE `message` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(10) DEFAULT NULL COMMENT '姓名',
  `number` varchar (10) DEFAULT NULL COMMENT '号码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

添加两条数据:

在这里插入图片描述
项目结构:
spring boot+swagger实现数据库增删查改_第1张图片
配置文件:
pom配置:
如果新建springboot项目,很多依赖会自动生成

 
   
     
           org.springframework.boot
           spring-boot-starter-web
       
     
      org.springframework.boot
      spring-boot-starter-test
      test


 
           org.springframework.boot
           spring-boot-devtools
           true 
         
       
       
       
           org.springframework.boot
           spring-boot-starter-data-jpa
       
         
       
           org.mybatis.spring.boot
           mybatis-spring-boot-starter
           ${mybatis-spring-boot}
       
       
       
           mysql
           mysql-connector-java
       
     
         io.springfox
         springfox-swagger2
         2.7.0
     
     
         io.springfox
         springfox-swagger-ui
         2.7.0
     
 

application.properties配置:

server.port=8083

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

启动类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main( String[] args ){
       // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
      SpringApplication.run(App.class, args);
      System.out.println("程序正在运行...");
    }
}

创建实体类:

package com.example.entity;

public class User {
    /** 编号 */
    private int id;
    /** 姓名 */
    private String name;
    /** 年龄 */
    private String number;
    
    public User(){
    }
    /**
     *  构造方法
     * @param id  编号
     * @param name  姓名
     */
   public User(int id, String name) {
      super();
      this.id = id;
      this.name = name;
   }

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getNumber() {
      return number;
   }

   public void setNumber(String number) {
      this.number = number;
   }
}

Dao层代码:

package com.example.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.entity.User;

/**
* 用户数据接口
 */
@Mapper
public interface UserDao {
   
   /**
    * 用户数据新增
    */
    @Insert("insert into message(id,name,number) values (#{id},#{name},#{number})")
     void addUser(User user); 
    
    /**
     * 用户数据修改
     */
    @Update("update message set name=#{name},number=#{number} where id=#{id}")
     void updateUser(User user);

    /**
     * 用户数据删除
    */
    @Delete("delete from message where id=#{id}")
    void deleteUser(int id);
   
    /**
     * 根据用户名称查询用户信息
     *
     */
    @Select("SELECT id,name,number FROM message where name=#{userName}")
    User findByName(String userName);
   
    /**
     * 查询所有
     */
    @Select("SELECT id,name,number FROM message")
    List findAll();
    
}

service接口:

package com.example.service;

import java.util.List;
import com.example.entity.User;
/**
* 用户接口
 */
public interface UserService {
   /**
    * 新增用户
    * @param user
    * @return
    */
   boolean addUser(User user);
   /**
    * 修改用户
    * @param user
    * @return
    */
   boolean updateUser(User user);
   /**
    * 删除用户
    * @param id
    * @return
    */
   boolean deleteUser(int id);
   
    /**
     * 根据用户名字查询用户信息
     * @param userName
     */
   User findUserByName(String userName);
    
    /**
     * 查询所有
     * @return
     */
   List findAll();

}

ServiceImpl:

package com.example.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.service.UserService;

/**
* 用户操作实现类
 */
@Service
public class UserServiceImpl implements UserService {
   @Autowired
    private UserDao userDao;
   
   
   @Override
   public boolean addUser(User user) {
      boolean flag=false;
      try{
         userDao.addUser(user);
         flag=true;
      }catch(Exception e){
         System.out.println("新增失败!");
         e.printStackTrace();
      }
      return flag;
   }

   @Override
   public boolean updateUser(User user) {
      boolean flag=false;
      try{
         userDao.updateUser(user);
         flag=true;
      }catch(Exception e){
         System.out.println("修改失败!");
         e.printStackTrace();
      }
      return flag;
   }

   @Override
   public boolean deleteUser(int id) {
      boolean flag=false;
      try{
         userDao.deleteUser(id);
         flag=true;
      }catch(Exception e){
         System.out.println("删除失败!");
         e.printStackTrace();
      }
      return flag;
   }

   @Override
   public User findUserByName(String userName) {
      return userDao.findByName(userName);
   }

   @Override
   public List findAll() {
      return userDao.findAll();
   }
}

swagger:
注意:这个要放到启动类同一层

package com.example;

/**
 * Created by win10 on 2019/9/2.
 */

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 SwaggerConfiguration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.web")) //Controller所在包(必须新建包)
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("信息的增删查改")  //标题
                .description("数据库表中信息的增删查改")  //描述
                .version("1.0")
                .build();
    }
}

Controller:

package com.example.web;

import java.util.List;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.entity.User;
import com.example.service.UserService;

/**
* 用户控制层
 */
@RestController
@RequestMapping(value = "/api")
public class userRestController {
   @Autowired
    private UserService userService;

    @ApiOperation(value = "添加新的信息")
   @RequestMapping(value = "/user", method = RequestMethod.POST)
    public boolean addUser(@RequestBody User user) {
       System.out.println("开始新增...");
        return userService.addUser(user);
    }

    @ApiOperation(value = "更新信息")
   @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public boolean updateUser(@RequestBody User user) {
       System.out.println("开始更新...");
        return userService.updateUser(user);
    }

    @ApiOperation(value = "根据id删除信息")
   @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    public boolean delete(@RequestParam(value = "userId", required = true) int userId) {
       System.out.println("开始删除...");
        return userService.deleteUser(userId);
    }

    @ApiOperation(value = "根据姓名查询信息")
    @RequestMapping(value = "/username", method = RequestMethod.GET)
    public User findByUserName(@RequestParam(value = "userName", required = true) String userName) {
       System.out.println("开始查询...");
        return userService.findUserByName(userName);
    }

    @ApiOperation(value = "查询全部信息")
    @RequestMapping(value = "/userAll", method = RequestMethod.GET)
    public List findByUserAge() {
       System.out.println("开始查询所有数据...");
        return userService.findAll();
    }
}

运行,,,
spring boot+swagger实现数据库增删查改_第2张图片
浏览器输入:http://localhost:8083/swagger-ui.html

spring boot+swagger实现数据库增删查改_第3张图片
先测试查询全部信息:
spring boot+swagger实现数据库增删查改_第4张图片
spring boot+swagger实现数据库增删查改_第5张图片
添加:
spring boot+swagger实现数据库增删查改_第6张图片
try out it!会返回true
此时数据库表信息:
在这里插入图片描述
删除信息:
spring boot+swagger实现数据库增删查改_第7张图片
返回true
数据库表信息:
在这里插入图片描述

OK啦,到此结束!

你可能感兴趣的:(Spring,boot)