SpringBoot制作简易查询接口

514 阅读2分钟

说明

不会搭建项目的同学请点开我个人中心看我第一篇springboot的博客

前两章我们做了登陆注册,按照程序下边登陆后应该要查询数据,所以抽出两章来做查询以及链表查询 本章先来做一个简单的查询功能

mysql语句

学过上一章的人也许发现问题了,接口返回的格式基本都是固定的,例如

首先建表添加数据

CREATE TABLE `book` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `author` varchar(30) NOT NULL,
  `date` datetime NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
INSERT INTO `book` (`id`, `name`, `author`, `date`) VALUES
(1, 'Android开发', '作者1', '2021-03-06 12:22:27'),
(2, 'Flutter开发', '作者2', '2021-03-20 12:22:33'),
(3, 'Spring开发', '作者3', '2021-03-12 12:22:38');

添加Book实体类

import lombok.Data;

@Data//自动生成get set
public class Book {
    private int id;
    private String name;//书名
    private String author;//作者
    private String date;//创建时间
}

添加 BookMapper

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import www.td0f7.cn.springboot.springboot.entity.Book;

import java.util.List;

@Mapper
public interface BookMapper {
    @Select("select * from book")
    List<Book> findALl();
}

由于查询表内所有内容,返回数据有可能是多行,所以返回值是 List

添加BookController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import www.td0f7.cn.springboot.springboot.base.BaseResult;
import www.td0f7.cn.springboot.springboot.entity.Book;
import www.td0f7.cn.springboot.springboot.mapper.BookMapper;

import java.util.List;

@RestController
@RequestMapping("book")
public class BookController {
    @Autowired(required = false)
    private BookMapper mapper;

    @GetMapping
    public BaseResult findAll() {
        List<Book> books = mapper.findALl();
        if (books == null || books.size() == 0) return new BaseResult(500, "没有查询到数据!", "");

        return new BaseResult(200, "", books);
    }
}

由于只有一个get方法,所以用指定别名,只需要@GetMapping!

接下来测试一下

在这里插入图片描述

返回值

{
    "code": 200,
    "msg": "",
    "data": [
        {
            "id": 1,
            "name": "Android开发",
            "author": "作者1",
            "date": "2021-03-06 12:22:27"
        },
        {
            "id": 2,
            "name": "Flutter开发",
            "author": "作者2",
            "date": "2021-03-20 12:22:33"
        },
        {
            "id": 3,
            "name": "Spring开发",
            "author": "作者3",
            "date": "2021-03-12 12:22:38"
        }
    ]
}

大家发现这个查询过于简单,如果有一个需求,需要查询a表的时候带出b表对象,也就是外键约束,怎么来做?我们下长讲解

bilibili视频教程同步更新