还不会写springboot接口?来我教你

Posted 捕風捉影

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了还不会写springboot接口?来我教你相关的知识,希望对你有一定的参考价值。

首先要明白数据的流通方向


数据的触发是前端请求后端引起的,遵循传统的mvc规范的话 我们需要pojo mapper service controller 四个层次,Pojo 是于数据库中字段直接对应的

在线搭建一个springboot项目

https://start.spring.io/
其中需要加入的四个依赖

点击确定 把没有用的文件删除 最后保留一下两个


在此处添加jdk的版本

开始编写接口实现

pon.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
server:
  port: 8001

持久层

package com.example.demo.entity;

import lombok.Data;

@Data
public class User 
    private Integer id;
    private String name;
    private String address;
    private Integer age;
    private String sex;
    private String phone;


这里我们引入了 lombok 不需要写get和set方法简化代码

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.10</version>
    <scope>provided</scope>
</dependency>

mapper层

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

public interface UserMapper 

    @Select("select * from user")
    List<User> findAll();

    @Update("INSERT INTO `user` (`name`, `address`, `age`, `sex`, `phone`) VALUES (#name,#address,#age,#sex,#phone);")
    @Transactional
    void save(User user);


    @Update("update user set name=#name , address=#address, age=#age, sex=#sex,phone=#phone where id =#id")
    @Transactional
    void updateById(User user);


    @Delete("delete from user where id =#id")
    @Transactional
    void deleteById(Long id);



    @Select("select * from user where id =#id")
    User findById(Long id);




    @Select("select * from user limit #offset,#pageSize")
    List<User> findByPage(Integer offset, Integer pageSize);

    @Select("select count(id) from user")
    Integer countUser();


controller

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.vo.Page;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController 
    
    @Resource
    UserMapper userMapper;
    @GetMapping
    public List<User> getUser() 
        return userMapper.findAll();
    

    @PostMapping
    public String addUser(@RequestBody User user)
        //把前端传过来的数据转化为user实体类的对象插入到数据库中
        userMapper.save(user);
        return "success";


    
    @PutMapping
    public String updateUser(@RequestBody User user)
        userMapper.updateById(user);
        return "success";
    

    @DeleteMapping("/id")  //一一对相应的关系
    public String deleteUser(@PathVariable("id") Long id)
        //注解是循序json回传带有id
        userMapper.deleteById(id);
        return "success";
    
    @GetMapping("/id")  //把返回的结果 返回出来 包装成一个user对象
    public User findById(@PathVariable("id") Long id)
        //注解是循序json回传带有id
        return userMapper.findById(id);
    



    @GetMapping("/page")
    public Page<User> findByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) 
        Integer offset = (pageNum - 1) * pageSize;
        List<User> userData = userMapper.findByPage(offset, pageSize);
        Page<User> page = new Page<>();
        page.setData(userData);

        Integer total = userMapper.countUser();
        page.setTotal(total);
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        return page;
    






注意 在实现过程中需要抓启动类中添加 扫描mapper的注解

以前就是对接口的增删改查 和分页查询的实现

实现过程

快速写出插入语句

插入实现 模拟前端想后端发送json数据

更新测试


删除实现


删除是要注意 id的一一对应

分页查询

分页查询 参数1 第几页 参数2 一页有多少个数据

以上是关于还不会写springboot接口?来我教你的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot系列(四十三):如何集成ElasticSearch,不会我教你|超级详细,建议收藏

springboot系列(十九):如何集成redis?不会我教你 | 超级详细,建议收藏

springboot系列(十九):如何集成redis?不会我教你 | 超级详细,建议收藏

蓝桥杯就要开赛了,填空题还不会?我教你一篇学会填空题,从此填空满分,信心大涨

基础篇:异步编程不会?我教你啊!CompeletableFuture

不会全排列算法(Javascript实现),我教你呀!