找回 Controller 、Service 、Model、 Repository熟悉的感觉
  • Controller: 请求的入口(路由分发映射的文件)
  • Service: 业务逻辑处理与数据仓库交互
  • Model: 实体与数据库中的表对应
  • Repository: 数据仓库
环境
  • Mac
  • mysql5.8
  • Idea
  • jdk1.8
  • Maven 3.8.6
创建数据库test 导入数据库连接坐标和依赖

pom.xml

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>    <!-- 不加版本号 application.yml配置文件,数据库驱动爆红 -->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
在 resources 新建application.yml配置数据库连接信息

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

在  src -> main -> java -> com.learn.demo 包目录下新建 controller、dao、models、service、service/Impl 包

models/UserModel 实体类 - 对应数据库中的数据表

package com.learn.demo.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class UserModel {
      
        

    @Id
    @GeneratedValue
    private Integer id;

    private String username;

    private String password;

    public UserModel() {
      
        
    }

    public Integer getId() {
      
        
        return id;
    }

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

    public String getUsername() {
      
        
        return username;
    }

    public void setUsername(String username) {
      
        
        this.username = username;
    }

    public String getPassword() {
      
        
        return password;
    }

    public void setPassword(String password) {
      
        
        this.password = password;
    }
}

dao/UserRepository

package com.learn.demo.dao;

import com.learn.demo.models.UserModel;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<UserModel, Integer> {
      
        
}

service/UserService 接口

package com.learn.demo.service;

import com.learn.demo.models.UserModel;

import java.util.List;
import java.util.Optional;

public interface UserService {
      
        

    UserModel createService(String username, String password);

    Optional<UserModel> getUserByIdService(Integer id) throws Exception;

    List<UserModel> listService();

    UserModel updateUserById(Integer id, String username, String password) throws Exception;

    boolean delUserByIdService(Integer id) throws Exception;

}

service/Impl/UserServiceImpl 接口的实现

package com.learn.demo.service.Impl;

import com.learn.demo.dao.UserRepository;
import com.learn.demo.models.UserModel;
import com.learn.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
      
        

    @Autowired
    private UserRepository userRepository;

    /** * * @param username * @param password * @return */
    public UserModel createService(String username, String password) {
      
        
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        return userRepository.save(userModel);
    }

    /** * * @param id * @return * @throws Exception */
    public Optional<UserModel> getUserByIdService(Integer id) throws Exception{
      
        
        if (id == null) {
      
        
            throw new IllegalArgumentException("Parameter id can't be null");
        }
        return userRepository.findById(id);
    }

    /** * * @return */
    public List<UserModel> listService() {
      
        
        return userRepository.findAll();
    }


    /** * * @param id * @param username * @param password * @return * @throws Exception */
    public UserModel updateUserById(Integer id, String username, String password) throws Exception {
      
        
        if (id == null) {
      
        
            throw new IllegalArgumentException("Parameter id can't be null");
        }

        Optional<UserModel> optional = userRepository.findById(id);

        if (optional.isPresent()) {
      
        
            UserModel userModel = optional.get();
            userModel.setUsername(username);
            userModel.setPassword(password);
            return userRepository.save(userModel);
        }

        return null;
    }

    /** * * @param id * @return * @throws Exception */
    public boolean delUserByIdService(Integer id) throws Exception {
      
        
        if (id == null) {
      
        
            throw new IllegalArgumentException("Parameter id can't be null");
        }
        userRepository.deleteById(id);
        return true;
    }

}

controller/UserController

package com.learn.demo.controller;

import com.learn.demo.models.UserModel;
import com.learn.demo.service.Impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
public class UserController {
      
        

    @Autowired
    private UserServiceImpl userServiceImpl;

    /** * 创建用户 * @param username * @param password * @return */
    @PostMapping("/create")
    public UserModel create(@RequestParam("username") String username,
                            @RequestParam("password") String password) {
      
        
        return userServiceImpl.createService(username, password);
    }

    /** * 通过ID获取用户信息 * @param id * @return */
    @GetMapping("/get/user/{id}")
    public Optional<UserModel> getUserById(@PathVariable("id") Integer id) throws Exception{
      
        
        return userServiceImpl.getUserByIdService(id);
    }

    /** * 用户列表 * @return */
    @GetMapping("/user/list")
    public List<UserModel> list() {
      
        
        return userServiceImpl.listService();
    }

    /** * 通过ID修改用户信息 * @param id * @param username * @param password * @return */
    @PutMapping("/update/user/{id}")
    public UserModel updateUserById(@PathVariable("id") Integer id,
                                    @RequestParam("username") String username,
                                    @RequestParam("password") String password) throws Exception{
      
        


        return userServiceImpl.updateUserById(id, username, password);
    }

    /** * 通过ID删除用户信息 * @param id * @return */
    @DeleteMapping("/del/user/{id}")
    public boolean delUserById(@PathVariable("id") Integer id) throws Exception {
      
        
        return userServiceImpl.delUserByIdService(id);
    }
}

测试

通过curl 或者 postman 依次执行以下API (parameters can’t be not null)
localhost:8080/create - POST
localhost:8080/get/user/id - GET
localhost:8080/user/list - GET
localhost:8080/update/user/id - PUT
localhost:8080/del/user/id - DELETE