SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查

前言

Spring boot项目目前是Java Web开发领域最受市场欢迎的Spring框架之一,也是构建分布式项目、微服务项目重要基础之一,Spring Boot免去了配置繁杂的依赖和配置,使得开发人员把更多的精力放在项目本身上,就Spring框架而言,Spring Boot可谓是集大成者,担负着敏捷开发,前后台分离、模块低耦合的神圣使命;麻将哥也是一个忠实的SpringBoot fans,这篇教程零基础的带大家从新建项目开始,完成一个流程的CRUD。本教程采用Spring Boot+Mybatis+Mysql实现,麻将哥MySql的版本是5.7,建议大家的Mysql是5.7或者5.7+。需要完整源码的小伙伴可以关注麻将哥的微信公众号“码匠心”自行获取,谢谢大家!

 

准备工作

编辑器:InteIIiJ IDEA

MySql数据库表设计:

SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查_第1张图片

IDEA新建Spring Boot 项目这篇文章就不再累赘,需要的小伙伴可以查看麻将哥的上一篇的博客。

构建项目

  1. 使用IDEA新建项目后,目录结构如下:

      SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查_第2张图片

    2.在curddemo目录新建5个package,分别为bean,config,controller,mapper,service,bean主要用来放置实体类文件,config要来放置放置Swagger接口文档的配置类文件,controller用来放置程序控制器(API)类文件,service用来放置处理业务逻辑的类文件,mapper用来放置于数据库映射相关的类文件。建成项目目录如下:

SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查_第3张图片

2.在pom.xml文件下添加以下依赖:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.9.RELEASE
         
    
    com.yisio
    curddemo
    0.0.1-SNAPSHOT
    curddemo
    Demo project for Spring Boot

    
        1.8
    

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

        
            org.springframework.boot
            spring-boot-starter-undertow
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        
        
            org.springframework.boot
            spring-boot-starter-websocket
        
        
            org.apache.poi
            poi
            3.17
        
        
            org.springframework.boot
            spring-boot-starter-mail
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-websocket
        
        
            org.springframework.boot
            spring-boot-starter-cache
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        


        
        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        
        
        
            com.alibaba
            druid
            1.1.10
        
       
        
            mysql
            mysql-connector-java
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
        
            
                src/main/java
                
                    **/*.xml
                
            
            
                src/main/resources
            
        
    


 3.在resources目录的application.properties文件里配置mysql连接信息:

#Created by 码匠心 on 2019/10/05.
#MySQL配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?serverTimezone=UTC&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
#MyBatis日志配置
mybatis.config-location=classpath:/mybatis-config.xml
#端口配置
server.port=8080
4.在resources目录下新建mybatis日志文件mybatis-config.xml




    
        
    

5.在bean目录下新建实体类User.java

package com.yisio.curddemo.bean;
/**
 * Created by 码匠心 on 2019/10/05.
 */
public class User {
    public Integer UserId;
    public String UserName;
    public boolean Sex;
    public boolean Wedlock;
    public String Place;
    public  void setUserId(Integer UserId){this.UserId=UserId;}
    public  void  setUserName(String UserName){this.UserName=UserName;}
    public  void  setSex(boolean Sex){this.Sex=Sex;}
    public  void  setWedlock(boolean Wedlock){this.Wedlock=Wedlock;}
    public  void  setPlace(String Place){this.Place=Place;}
}

6.在config目录下新建Swagger在线接口文档的配置文件SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {
        @Bean
        public Docket api(){
            return  new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build();
        }
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    //文档标题
                    .title(" Spring Boot RESTful API")
                    // 版本号
                    .version("1.0")
                    // 标题描述
                    .description("swagger在线文档")
                    .build();
        }
    }

7.在mapper目录下新建UserMapper接口文件,新建增删改查的四个方法

package com.yisio.curddemo.mapper;

import com.yisio.curddemo.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
 * Created by 码匠心 on 2019/10/05.
 */
import java.util.List;
@Mapper
public interface UserMapper {
     List getAllUser();
     int AddUser(User users);
     int updateUser(@Param("users") User users);
     int deleteUserByUserId(@Param("ids") String[] ids);
}

8.在mapper目录下新建UserMapper.xml文件,使用mybtis操作数据库





    
        
        
        
        
        
    
     
    
        insert into sysuser(UserName,Sex,Wedlock,Place)
        values(#{UserName,jdbcType=VARCHAR},
              #{Sex,jdbcType=BOOLEAN},
              #{Wedlock,jdbcType=BOOLEAN},
              #{Place,jdbcType=VARCHAR})
    
    
        update sysuser
        
            UserName=#{users.UserName,jdbcType=VARCHAR},
            Sex=#{users.Sex,jdbcType=BOOLEAN},
            Wedlock=#{users.Wedlock,jdbcType=BOOLEAN},
            Place=#{users.Place,jdbcType=VARCHAR}
        
        where UserId=#{users.UserId,jdbcType=INTEGER}
    
    
         DELETE  from sysuser where UserId in
        
            #{id}
        
    

9.在service目录下新建业务逻辑类UserService.java

package com.yisio.curddemo.service;

import com.yisio.curddemo.bean.User;
import com.yisio.curddemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/**
 * Created by 码匠心 on 2019/10/05.
 */
@Service
@Transactional
public class UserService {
    @Autowired
    UserMapper userMapper;
    public List getAllUser(){
        return userMapper.getAllUser();
    }
    private  void UserDo(User users)
    {
        users.setUserId(users.UserId);
        users.setUserName(users.UserName);
        users.setPlace(users.Place);
        users.setSex(users.Sex);
        users.setWedlock(users.Wedlock);
    }
    public int AddUser(User users)  {
        UserDo(users);
        return userMapper.AddUser(users);
    }
    public  int updateUser(User users){
        UserDo(users);
        return userMapper.updateUser(users);
    }
    public  boolean deleteUserByUserId(String ids){
      String[] split = ids.split(",");
      return userMapper.deleteUserByUserId(split) == split.length;
    }
}

10.在controller目录下新建业务接口类UserController.java

package com.yisio.curddemo.controller;

import com.yisio.curddemo.bean.User;
import com.yisio.curddemo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
/**
 * Created by 码匠心 on 2019/10/05.
 */
@RestController
@RequestMapping("/User/UserData")
@Api(value = "UserController",description = "用户管理")
public class UserController {
    @Autowired
    UserService userService;

    @ApiOperation(value = "用户查询")
    @RequestMapping(value = "/UserData",method = RequestMethod.GET)
    public Map getAllUser(){
          Map map=new HashMap<>();
          map.put("User",userService.getAllUser());
          return map;
    }
    @ApiOperation(value = "新增用户")
    @RequestMapping(value = "/UserData/AddUser",method = RequestMethod.POST)
    public String AddUser(User users) { 
        if (userService.AddUser(users)==1)
            return "新增成功!";
        return  "新增失败!";
    }
    @ApiOperation(value = "修改用户")
    @RequestMapping(value = "/UserData/updateUser",method = RequestMethod.PUT)
    public String updateUser(User users){
        if (userService.updateUser(users)==1)
            return "修改成功!";
        return "修改失败!";
    }
    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "/UserData/deleteUser/{ids}",method = RequestMethod.DELETE)
    public String deleteUserByUserId(@PathVariable String ids){
        if(userService.deleteUserByUserId(ids))
          return "删除成功!";
        return "删除失败!";
    }
}

10.最后的项目结构如下:

SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查_第4张图片

11.点击右上角项目启动按钮,运行项目,启动窗口看到如下信息则说明项目启动成功

SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查_第5张图片

12.在浏览器里输入URL:http://localhost:8080/swagger-ui.html#/,Swagger界面如下:

SpringBoot实战系列1:Spring Boot+Mybatis+MySql实现增删改查_第6张图片

到这里我们的项目就启动成功了,执行Swagger接口文档里面的各个接口就能执行相应的增删改查操作!

如果需要完整的源码的小伙伴可关注麻将哥的微信公众号“码匠心”,自行获取,谢谢大家!

 

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