Springboot+mysql+CRUD(增删改查)

talk is cheap,show you my code
源码:springboot-mysql-crud

1.创建springboot项目
2.导入相关依赖


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.5.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.wantaogroupId>
    <artifactId>springboot-mysql-crudartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>springboot-mysql-crudname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
            <version>2.1.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.0.0version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

注意:我使用了lombok插件(自动生成get,set方法等),不会用的请自行百度

3.新建一个数据库(springboot-mysql-crud),建一张表user(id,username,password)

4.在配置文件application.properties里面写相关配置

#mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/springboot-mysql-crud?useSSL=false
spring.datasource.username=root
spring.datasource.password=#你自己的数据库密码

#mybatis
mybatis.configuration.map-underscore-to-camel-case=true

#server
server.servlet.context-path=/

5.建立bean包,新建类User
注意:我使用了lombok插件(自动生成get,set方法等),不会用的请自行百度或者你自己生成get,set方法

package com.wantao.springbootmysqlcrud.bean;

import lombok.Data;
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
}

6.建立dao包,新建CRUDDao用注解的方式写对应sql语句

package com.wantao.springbootmysqlcrud.dao;

import com.wantao.springbootmysqlcrud.bean.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface CRUDDao {
     @Select("select * from user")
     List<User> getAllUser();
     @Select("select * from user where id =#{id}")
     User getUserById(@Param("id") Integer id);
     @Insert("insert into user(id,username,password) values(#{id},#{username},#{password})")
     int addUser(User user);
     @Update("update user set username=#{username},password=#{password} where id=#{id}")
     int updateUser(User user);
     @Delete("delete from user where id=#{id}")
     int deleteUser(@Param("id") Integer id);
}


7.建立service包,新建CRUDService类,实现CRUDDao接口

package com.wantao.springbootmysqlcrud.CRUDService;

import com.wantao.springbootmysqlcrud.bean.User;
import com.wantao.springbootmysqlcrud.dao.CRUDDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CRUDService implements CRUDDao {
    @Autowired
    private CRUDDao crudDao;
    @Override
    public List getAllUser() {
        return crudDao.getAllUser();
    }

    @Override
    public User getUserById(Integer id) {
        return crudDao.getUserById(id);
    }

    @Override
    public int addUser(User user) {
        return crudDao.addUser(user);
    }

    @Override
    public int updateUser(User user) {
        return crudDao.updateUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        return crudDao.deleteUser(id);
    }
}

8.为了数据更好的显示,建立result包,新建Result类(用来对返回的json进行封装)

package com.wantao.springbootmysqlcrud.result;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回的Json数据封装
 */
@Data
@NoArgsConstructor
public class Result{
    private Integer code;
    private String msg;
    private Map<String, Object> data = new HashMap<String, Object>();

    /**
     * 成功时调用
     * 默认状态码:200
     */
    public static Result success() {
        Result result = new Result();
        result.setCode(200);
        result.setMsg("处理成功");
        return result;
    }

    /**
     * 失败时调用
     * 默认状态码:500
     */
    public static Result error() {
        Result result = new Result();
        result.setCode(500);
        result.setMsg("处理失败");
        return result;
    }

    /**
     * 设置数据
     * @param key
     * @param value
     * @return
     */
    public Result add(String key,Object value){
        this.data.put(key,value);
        return this;
    }

}

9.建立controller包,新建CRUDController类.

package com.wantao.springbootmysqlcrud.controller;

import com.wantao.springbootmysqlcrud.CRUDService.CRUDService;
import com.wantao.springbootmysqlcrud.bean.User;
import com.wantao.springbootmysqlcrud.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class CRUDController {
    @Autowired
    private CRUDService crudService;

    /**
     * 查询一个用户
     * @param id
     * @return
     */
    @GetMapping("/getUserById/{id}")
    public Result getUserById(@PathVariable("id")Integer id){
        User user=crudService.getUserById(id);
        return Result.success().add("user",user);
    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/getAllUser")
    public Result getAllUser(){
        List<User> users=crudService.getAllUser();
        return Result.success().add("user",users);
    }

    @GetMapping("/addUser")
    public Result addUser(){
        User user=new User();
        user.setId(2);
        user.setUsername("selenium1");
        user.setPassword("123");
        crudService.addUser(user);
        return Result.success();
    }

    @GetMapping("/updateUser")
    public Result updateUser(){
        User user=new User();
        user.setId(1);
        user.setUsername("seleniumupdate");
        user.setPassword("123");
        crudService.updateUser(user);
        return Result.success();
    }

    @GetMapping("/deleteUser/{id}")
    public Result deleteUser(@PathVariable("id") Integer id){
        crudService.deleteUser(id);
        return Result.success();
    }



}


这就大功告成了!!!(撒花.gif)

下面放一下结果图

1.查询一个用户
Springboot+mysql+CRUD(增删改查)_第1张图片
2.新增一名用户(查询所有用户可以看出我们新增进去了)
Springboot+mysql+CRUD(增删改查)_第2张图片
3.查询所有用户
Springboot+mysql+CRUD(增删改查)_第3张图片
4.修改用户(可以看出用户1被修改了)
Springboot+mysql+CRUD(增删改查)_第4张图片
5.删除用户(可以看出用户2被删除了)
Springboot+mysql+CRUD(增删改查)_第5张图片
源码:springboot-mysql-crud

你可能感兴趣的:(springboot)