springboot中controller层接收参数,servers层调用mapper层,一条sql搞定排序

2023-05-16

前言
很多小伙伴们在公司不管是测试C端产品还是B端产品,都会测到排序的业务需求;那么我们就会好奇排序是如何实现的呢?下面我们开始介绍代码的实现

数据库建表
我们需要创建一个书籍book表结构,如下图所示

CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT comment '主键自增id',
`book_no` varchar(200) comment '书的编号',
`book_name` varchar(200) NOT NULL comment '书名',
`book_author` varchar(200) DEFAULT NULL comment '书的作者',
`book_publish` varchar(200) DEFAULT NULL comment '书的出版社',
`book_category` int(11) DEFAULT NULL comment '书的分类',
`book_price` varchar(20) DEFAULT NULL comment '书的价格',
`book_introduction` text DEFAULT NULL comment '书的介绍',
create_time timestamp not null default current_timestamp comment '创建时间',
update_time timestamp not null default current_timestamp on update current_timestamp comment '更新时间',
PRIMARY KEY (`id`),
KEY `book_category` (`book_category`) USING BTREE,
CONSTRAINT `book_ibfk_1` FOREIGN KEY (`book_category`) REFERENCES `book_category` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment '书的信息';

向book表里插入数据

insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction) 
values('1111','巨人的陨落','肯.福莱特','江苏凤凰文艺出版社',1,'129','一本文学巨作');
insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction) 
values('2222','巨人的陨落2','肯.福莱特','江苏凤凰文艺出版社',1,'129','一本文学巨作');
insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction)
values('3333','巨人的陨落3','肯.福莱特','江苏凤凰文艺出版社',1,'129','一本文学巨作');
insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction) 
values('4444','巨人的陨落4','肯.福莱特','江苏凤凰文艺出版社',1,'129','一本文学巨作');
insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction)
values('5555','巨人的陨落5','肯.福莱特','江苏凤凰文艺出版社',1,'129','一本文学巨作');
insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction) 
values('6666','巨人的陨落6','肯.福莱特','江苏凤凰文艺出版社',1,'129','一本文学巨作');
insert into book(book_no,book_name,book_author,book_publish,book_category,book_price,book_introduction) 
values('7777','巨人的陨落7','张三','江苏凤凰文艺出版社',1,'129','一本文学巨作');

创建mapper.xml文件

  • include标签语法:include是引用SQL代码,refid 是引用的sql的id名称,一定要唯一
  • where标签语法:是顶层的遍历标签,需要配合if标签使用,单独使用无意义。
  • if标签语法:主要用来进行条件查询或者解决空值插入。具体语法为:<if test="校验条件">sql语句</if>
  • resultType标签语法:当数据表中字段的名称和实体类的属性名一致时,MyBatis会自动把查询结果集中的属性赋值给和bean对象类中的属性名一致的字段。可以使用此标签进行映射

resultMap标签语法:当数据表中字段的名称和实体类的属性名不一致时,使用此标签进行映射。
语法格式:
<resultMap type="实体类" id="唯一的标志"><result column="数据表字段" property="实体属性"/></resultMap>
这个id是resultMap的唯一标识 在select标签要引用这个resultMap时 靠这个id来引用就行
<select id="getBookList" resultMap="bookMap">

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.o2o.mapper.BookMapper">
    <!-- 书籍对象映射 -->
    <resultMap id="bookMap" type="com.o2o.data.Book">
        <id column="id" property="id"/>
        <id column="book_no" property="bookNo"/>
        <id column="book_name" property="bookName"/>
        <id column="book_author" property="bookAuthor"/>
        <id column="book_publish" property="bookPublish"/>
        <id column="book_category" property="bookCategory"/>
        <id column="book_price" property="bookPrice"/>
        <id column="book_introduction" property="bookIntroduction"/>
        <id column="category_name" property="categoryName"/>
        <id column="create_time" property="createTime"/>
        <id column="update_time" property="updateTime"/>
    </resultMap>

    <!-- 书籍对象映射 -->
    <resultMap type="com.o2o.data.BookWithBorrowFlg" id="bookWithBorrowFlgMap">
        <id column="id" property="id"/>
        <id column="book_no" property="bookNo"/>
        <id column="book_name" property="bookName"/>
        <id column="book_author" property="bookAuthor"/>
        <id column="book_publish" property="bookPublish"/>
        <id column="book_category" property="bookCategory"/>
        <id column="book_price" property="bookPrice"/>
        <id column="book_introduction" property="bookIntroduction"/>
        <id column="category_name" property="categoryName"/>
        <id column="create_time" property="createTime"/>
        <id column="update_time" property="updateTime"/>
        <id column="username" property="username"/>
        <id column="borrow_flg" property="borrowFlg"/>
    </resultMap>

    <!-- 按照查询条件分页查询书籍  -->
     <select id="getBookList" resultMap="bookMap">
         select
         a.id,a.book_no,a.book_name,a.book_author,a.book_publish,a.book_price,a.book_introduction,b.category_name
         from
         book a
         inner join
         book_category b
         on a.book_category = b.category_id
         <include refid="getBooksWhere"></include>
         order by a.update_time desc
     </select>

    <!-- 获取书籍的动态where条件 -->
    <sql id="getBooksWhere">
    <where>
    1=1
        <if test="bookNo != null and bookNo != ''">
            and a.book_no like '%' #{bookNo} '%'
        </if>
        <if test="bookName != null and bookName != ''">
            and a.book_name like '%' #{bookName} '%'
        </if>
        <if test="bookAuthor != null and bookAuthor != ''">
            and a.book_author like '%' #{bookAuthor} '%'
        </if>
        <if test="bookPublish != null and bookPublish != ''">
            and a.book_publish like '%' #{bookPublish} '%'
        </if>
        <if test="bookCategory != null and bookCategory != ''">
            and a.book_category = #{bookCategory}
        </if>
    </where>
    </sql>
</mapper>

application.yml配置文件

  • driver-class-name: com.mysql.cj.jdbc.Driver
    mysql是8.x版本的需要加cj,如果是低版本5.x的不需要加这个cj
  • mapper-locations: classpath:/mapper/*.xml
    #classpath指的是resource文件夹指定mapper文件的位置,将配置路径下的*.xml文件加载到mybatis
  • map-underscore-to-camel-case: true
    开启驼峰命名规则 比如数据库字段是有下划线的t_no,那么代码中就要写成Tno代码里面自动把下划线的字母变成大写
server:
  port: 9527

# 数据源
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver  # mysql是8.x版本的需要加cj,如果是低版本5.x的不需要加这个cj
      url: jdbc:mysql://localhost:3306/cyw-mybatis?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8
      username: root
      password: ******


mybatis:
  #classpath指的是resource文件夹指定mapper文件的位置,将配置路径下的*.xml文件加载到mybatis
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    #开启驼峰命名规则 比如数据库字段是有下划线的t_no,那么代码中就要写成Tno代码里面自动把下划线的字母变成大写
    map-underscore-to-camel-case: true
    type-aliases-package: com.o2o.data


# 开启日志
logging:
  level:
    com:
      o2o:
        cy: debug

创建实体类book对象
@Data注解自动实现settergetter方法
在这里插入图片描述
创建接口统一返回类和枚举类
在这里插入图片描述
在这里插入图片描述

创建mapper层getBookList方法

package com.o2o.mapper;

import com.o2o.data.Book;
import com.o2o.data.param.BookParams;

import java.util.List;

/**
 * @Time : 2022/12/27 18:25
 * @Author : wcy
 * @FileName:
 * @email :954515472@qq.com
 */

public interface BookMapper {
    List<Book> getBookList(BookParams bookParams);
}

创建service层getBookList方法

package com.o2o.service;

import com.o2o.data.Book;
import com.o2o.data.param.BookParams;

import java.util.List;

/**
 * @Time : 2022/12/27 18:14
 * @Author : wcy
 * @FileName:
 * @email :954515472@qq.com
 */

public interface BookService {
    /**
     * 按照查询条件分页查询书籍
     */
    List<Book> getBookList(BookParams bookParams);
}

创建serviceImpl实现类
在service层中通过 @Resource注解注入mapper ,就可以直接通过mapper对象调用mapper接口中定义的方法,mapper中的方法名 与mapper.xml中的名字一一对应

package com.o2o.service.impl;

import com.o2o.data.Book;
import com.o2o.data.param.BookParams;
import com.o2o.mapper.BookMapper;
import com.o2o.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Time : 2022/12/27 18:27
 * @Author : wcy
 * @FileName:
 * @email :954515472@qq.com
 */

@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public List<Book> getBookList(BookParams bookParams) {
       return bookMapper.getBookList(bookParams);
    }

    @Override
    public Long getTotalCount(BookParams bookParams) {
        return bookMapper.getTotalCount(bookParams);
    }
}

创建controller层接收前端传入的参数

  • @Resource注解注入service层对象
  • public返回的是一个CommonResponse对象,因为我们查询全部getBookLists(BookParams bookParams)传了参,映射一个GetMapping请求方法,传入路径名“/getBookLists”
  • @ResponseBody注解将controller层的方法返回结果写入到响应正文response对象的body中,直接返回JSON数据
package com.o2o.controller;

import com.o2o.common.CommonResponse;
import com.o2o.data.Book;
import com.o2o.data.param.BookParams;
import com.o2o.service.BookService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @Time : 2022/12/27 18:04
 * @Author : wcy
 * @FileName:
 * @email :954515472@qq.com
 */

@RestController
@RequestMapping("book")
public class BookController {

    @Resource
    private BookService bookService;
    /**
     * 按照条件获取书籍信息
     * @param bookParams
     * @return
     */
    @GetMapping("/getBookLists")
    @ResponseBody //@ResponseBody注解将controller层的方法返回结果写入到响应正文response对象的body中,直接返回JSON数据
    public CommonResponse<List<Book>> getBookLists(BookParams bookParams) {
        // 按照查询条件分页查询书籍
        List<Book> books = bookService.getBookList(bookParams);
        CommonResponse response = CommonResponse.successInstance(books);
        return response;
    }
}

启动run
我们可以看到springboot已经运行成功啦
在这里插入图片描述
在浏览器输入{ip}+路径访问
在这里插入图片描述
到这里就大功告成啦!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot中controller层接收参数,servers层调用mapper层,一条sql搞定排序 的相关文章

随机推荐

  • mysql存储过程实现同时多表写入,构造创建商品数据

    前言 通常在做性能测试的过程中 xff0c 我们需要构造一下性能测试数据 xff0c 有些可以通过调用API xff0c 直接构造数据 xff0c 但是可能会存在一些场景 xff0c 需要我们直接在数据库中插入数据 xff0c 通常我们对于
  • MySQL修改root密码的多种方法,你掌握了吗

    前言 我们在工作中都会用到mysql数据库 xff0c 也是最熟悉用的最多的 xff0c 无论是在本地安装mysql还是在Linux安装mysql xff0c 都需要给数据库配置用户名和密码 xff0c 时间一长我们就会忘记配置数据库的密码
  • 性能测试:数据库架构和SQL优化

    前言 有时候我们出去面试的时候 xff0c 会被问到是否有做过架构方面的优化 如果没有准备突然被问到的话通常会有点懵 那么我们这里来整理一下系统架构优化相关的知识 其实一般架构优化主要就分为数据库架构 xff0c 第二个就是应用程序架构 数
  • springboot整合mybatis实现增删改查

    前言 在学习Springboot过程中 xff0c 整合mybatis框架实现表数据的增删改查 xff0c 话不多说 xff0c 开始贴代码 xff01 Spring Boot提供了一个名为spring boot starter paren
  • 国内个人免费在SCI、IEEE等数据库下载文献方法

    膜拜CSDN上的大神们 xff0c 在技术和方法上为我们奉献的力量 xff01 xff01 xff01 xff01 1 打开IEEE官网 xff1a https ieeexplore ieee org Xplore home jsp 用英文
  • springboot读取yml文件中的list列表、数组、map集合和对象

    前言 springboot配置文件yml类型简单的风格 xff0c 十分受大家的欢迎 xff0c 支持字符string类型 xff0c 支持列表list类型 xff0c 支持集合map类型 xff0c 支持数组array类型 xff0c 支
  • JMeter 线上压测如何预防服务器被打挂

    通常我们在做线上压测的时候 xff0c 会遇到一个问题 xff0c 就是担心在线上压测的时候服务器被我们压挂掉 xff0c 由于是线上服务器 xff0c 挂掉之后再重启 xff0c 会比较麻烦 xff0c 因此 JMeter 提供了一个方法
  • JMeter 进行函数助手MD5加密

    JMeter 函数助手 MD5 加密 JMeter函数助手中 xff0c 提供了MD5加密的方法 xff0c 如图所示 xff0c 我们将内容 123456 进行加密 xff0c 可以看到加密成功了 下面我们来看看项目接口的请求参数 这是一
  • mysql监控sql执行情况

    要想进阶针对mysql学习乃至掌握mysql调优的基本技能 xff0c 监控mysql的执行情况必不可少 就像我们的代码 xff0c 如果不能debug xff0c 想要进行调优排错 xff0c 难度将会大大增加 所以今天我们就来讲解如何监
  • Linux搭建JMeter环境(超详细)

    安装JDK 官网链接 xff1a https www oracle com java technologies javase javase jdk8 downloads html 因为我虚拟机配置是arm xff0c 安装 Linux环境下
  • 性能测试:数据库连接池问题分析

    前言 今天我们来压测一个支付的接口 xff0c 10个并发 xff0c 压测5分钟 下面我们可以看到tps大概在200多 xff0c 响应时间在40ms左右 下面我们来看一下服务器的性能 xff0c 应用服务器的cpu使用率大概在60 左右
  • 解决docker容器时间和宿主机时间不一致问题

    新建容器之后 xff0c 发现容器的时间和宿主机的容器不一致 xff0c 我们先看一下宿主机的时间 xff0c 现在是北京时间 进入容器之后 xff0c 查看容器时间和宿主机的时间不一致 xff0c 因为我现在容器的时间已经正常了 xff0
  • 性能测试:数据库性能问题实战分析

    接口压测分析 现在我们来压测一个获取用户信息接口 xff0c 这个接口会涉及到数据库的数据查询 我们的项目是部署正在应用服务器上面的 xff0c 因此我们需要同时监控应用服务器和数据库服务器 那么下面我们来看一下tomcat的这台服务器 x
  • Springboot封装HTTPClient中get,post,json,put请求方法

    pom xml依赖如下 span class token operator lt span span class token operator span span class token operator span https span c
  • Python实现列表数据按字典key值嵌套排序

    前言 当实现Python列表中的嵌套数据 xff0c 需要对数据进行排序 xff0c 是不是脑海中已经思考各种for循环或者while循环列表中的数据 xff0c 然后对列表中的数据进行排序 xff1f 小编今天在做可视化图表统计自动化的时
  • qemu-img 将iso转换成qcow2/raw

    参考 xff1a moonfly KVM虚拟机导出最小化体积的qcow2镜像文件 qemu不能直接将iso转化成qcow2或者raw xff0c 但是使用iso创建虚机后会产生qcow2 raw作为虚机的硬盘 xff0c 因此 xff0c
  • mac pro M1(ARM)安装vmware虚拟机及centos8详细教程

    前言 mac发布了m1芯片 xff0c 其强悍的性能收到很多开发者的追捧 xff0c 但是也因为其架构的更换 xff0c 导致很多软件或环境的安装成了问题 xff0c 这次我们接着来看如何在mac m1环境下安装centos8 Centos
  • prometheus+grafana对数据库mysql监控

    安装 mysql span class token function docker span run span class token parameter variable name span mysql test span class t
  • 性能测试:Redis性能监控(redis-stat工具)

    redis 监控 redis 监控一共有两种方式 xff0c 一种是通过info命令 xff0c 还有一种是使用redis stat工具 两者其实本质是一样的 xff0c 不过一个是命令行的模式下查看监控数据 xff0c 而另外一种是图形化
  • springboot中controller层接收参数,servers层调用mapper层,一条sql搞定排序

    前言 很多小伙伴们在公司不管是测试C端产品还是B端产品 xff0c 都会测到排序的业务需求 xff1b 那么我们就会好奇排序是如何实现的呢 xff1f 下面我们开始介绍代码的实现 数据库建表 我们需要创建一个书籍book表结构 xff0c