Sfoglia il codice sorgente

0601 查询接口实现

Qing 1 anno fa
parent
commit
ed2da46cb7

+ 19 - 0
novel-demo/src/main/java/com/sf/config/MybatisPlusConfig.java

@@ -0,0 +1,19 @@
+package com.sf.config;
+
+import com.baomidou.mybatisplus.annotation.DbType;
+import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
+import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class MybatisPlusConfig {
+
+    // 将拦截器注入到spring容器中
+    @Bean
+    public MybatisPlusInterceptor mybatisPlusInterceptor() {
+        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
+        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
+        return interceptor;
+    }
+}

+ 10 - 0
novel-demo/src/main/java/com/sf/controller/BookInfoController.java

@@ -1,9 +1,11 @@
 package com.sf.controller;
 
 import com.sf.dto.RestResp;
+import com.sf.dto.req.BookSearchReqDto;
 import com.sf.dto.resp.BookChapterRespDto;
 import com.sf.dto.resp.BookContentAboutRespDto;
 import com.sf.dto.resp.BookInfoRespDto;
+import com.sf.dto.resp.PageRespDto;
 import com.sf.entity.BookInfo;
 import com.sf.service.IBookChapterService;
 import com.sf.service.IBookContentService;
@@ -55,4 +57,12 @@ public class BookInfoController {
         BeanUtils.copyProperties(bookInfo,bookInfoRespDto);
         return RestResp.ok(bookInfoRespDto);
     }
+
+
+    // http://127.0.0.1:8888/api/front/search/books?keyword=&pageSize=10&pageNum=2
+    @GetMapping("/api/front/search/books")
+    public RestResp<PageRespDto<BookInfoRespDto>> searchBooks(BookSearchReqDto bookSearchReqDto){
+        PageRespDto<BookInfoRespDto> pageRespDto = bookInfoService.searchBooks(bookSearchReqDto);
+        return RestResp.ok(pageRespDto);
+    }
 }

+ 1 - 2
novel-demo/src/main/java/com/sf/controller/NewsContentController.java

@@ -25,8 +25,7 @@ public class NewsContentController {
     private INewsContentService newsContentService;
 
     @GetMapping("/api/front/news/{id}")
-    public RestResp<NewsInfoRespDto> getNews(
-            @PathVariable Long id) {
+    public RestResp<NewsInfoRespDto> getNews(@PathVariable Long id) {
         NewsInfoRespDto newsInfoRespDto = newsContentService.getNews(id);
         return RestResp.ok(newsInfoRespDto);
     }

+ 1 - 0
novel-demo/src/main/java/com/sf/controller/NewsInfoController.java

@@ -28,6 +28,7 @@ public class NewsInfoController {
     // http://127.0.0.1:8888/api/front/news/latest_list
     @GetMapping("/api/front/news/latest_list")
     public RestResp<List<NewsInfoRespDto>> listLatestNews() {
+        // ctrl+alt 可以直接进入实现类的方法中
         List<NewsInfoRespDto> newsInfoRespDtos = newsInfoService.listLatestNews();
         return RestResp.ok(newsInfoRespDtos);
     }

+ 83 - 0
novel-demo/src/main/java/com/sf/dto/req/BookSearchReqDto.java

@@ -0,0 +1,83 @@
+package com.sf.dto.req;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.v3.oas.annotations.Parameter;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import java.util.Date;
+
+/**
+ * 小说搜索 请求DTO
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/16
+ */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class BookSearchReqDto extends PageReqDto {
+
+    /**
+     * 搜索关键字
+     */
+    @Parameter(description = "搜索关键字")
+    private String keyword;
+
+    /**
+     * 作品方向
+     */
+    @Parameter(description = "作品方向")
+    private Integer workDirection;
+
+    /**
+     * 分类ID
+     */
+    @Parameter(description = "分类ID")
+    private Integer categoryId;
+
+    /**
+     * 是否收费,1:收费,0:免费
+     */
+    @Parameter(description = "是否收费,1:收费,0:免费")
+    private Integer isVip;
+
+    /**
+     * 小说更新状态,0:连载中,1:已完结
+     */
+    @Parameter(description = "小说更新状态,0:连载中,1:已完结")
+    private Integer bookStatus;
+
+    /**
+     * 字数最小值
+     */
+    @Parameter(description = "字数最小值")
+    private Integer wordCountMin;
+
+    /**
+     * 字数最大值
+     */
+    @Parameter(description = "字数最大值")
+    private Integer wordCountMax;
+
+    /**
+     * 最小更新时间
+     * 如果使用Get请求,直接使用对象接收,则可以使用@DateTimeFormat注解进行格式化;
+     * 如果使用Post请求,@RequestBody接收请求体参数,默认解析日期格式为yyyy-MM-dd HH:mm:ss ,
+     * 如果需要接收其他格式的参数,则可以使用@JsonFormat注解
+     * */
+    @Parameter(description = "最小更新时间")
+    @DateTimeFormat(pattern = "yyyy-MM-dd")
+    @JsonFormat(pattern = "yyyy-MM-dd")
+    private Date updateTimeMin;
+
+    /**
+     * 排序字段
+     */
+    @Parameter(description = "排序字段")
+    private String sort;
+}

+ 33 - 0
novel-demo/src/main/java/com/sf/dto/req/PageReqDto.java

@@ -0,0 +1,33 @@
+package com.sf.dto.req;
+
+import io.swagger.v3.oas.annotations.Parameter;
+import lombok.Data;
+
+/**
+ * 分页请求数据格式封装,所有分页请求的Dto类都应继承该类
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/11
+ */
+@Data
+public class PageReqDto {
+
+    /**
+     * 请求页码,默认第 1 页
+     */
+    @Parameter(description = "请求页码,默认第 1 页")
+    private int pageNum = 1;
+
+    /**
+     * 每页大小,默认每页 10 条
+     */
+    @Parameter(description = "每页大小,默认每页 10 条")
+    private int pageSize = 10;
+
+    /**
+     * 是否查询所有,默认不查所有 为 true 时,pageNum 和 pageSize 无效
+     */
+    @Parameter(hidden = true)
+    private boolean fetchAll = false;
+
+}

+ 64 - 0
novel-demo/src/main/java/com/sf/dto/resp/PageRespDto.java

@@ -0,0 +1,64 @@
+package com.sf.dto.resp;
+
+import lombok.Getter;
+
+import java.util.List;
+
+/**
+ * 分页响应数据格式封装
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/11
+ */
+@Getter
+public class PageRespDto<T> {
+
+    /**
+     * 页码
+     */
+    private final long pageNum;
+
+    /**
+     * 每页大小
+     */
+    private final long pageSize;
+
+    /**
+     * 总记录数
+     */
+    private final long total;
+
+    /**
+     * 分页数据集
+     */
+    private final List<? extends T> list;
+
+    /**
+     * 该构造函数用于通用分页查询的场景 接收普通分页数据和普通集合
+     */
+    public PageRespDto(long pageNum, long pageSize, long total, List<T> list) {
+        this.pageNum = pageNum;
+        this.pageSize = pageSize;
+        this.total = total;
+        this.list = list;
+    }
+
+    public static <T> PageRespDto<T> of(long pageNum, long pageSize, long total, List<T> list) {
+        return new PageRespDto<>(pageNum, pageSize, total, list);
+    }
+
+    /**
+     * 获取分页数
+     */
+    public long getPages() {
+        if (this.pageSize == 0L) {
+            return 0L;
+        } else {
+            long pages = this.total / this.pageSize;
+            if (this.total % this.pageSize != 0L) {
+                ++pages;
+            }
+            return pages;
+        }
+    }
+}

+ 5 - 0
novel-demo/src/main/java/com/sf/mapper/BookInfoMapper.java

@@ -1,9 +1,13 @@
 package com.sf.mapper;
 
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.sf.dto.req.BookSearchReqDto;
 import com.sf.entity.BookInfo;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import org.apache.ibatis.annotations.Mapper;
 
+import java.util.List;
+
 /**
  * <p>
  * 小说信息 Mapper 接口
@@ -16,4 +20,5 @@ import org.apache.ibatis.annotations.Mapper;
 //@Mapper
 public interface BookInfoMapper extends BaseMapper<BookInfo> {
 
+    List<BookInfo> searchBooks(IPage page, BookSearchReqDto dto);
 }

+ 4 - 0
novel-demo/src/main/java/com/sf/service/IBookInfoService.java

@@ -1,5 +1,8 @@
 package com.sf.service;
 
+import com.sf.dto.req.BookSearchReqDto;
+import com.sf.dto.resp.BookInfoRespDto;
+import com.sf.dto.resp.PageRespDto;
 import com.sf.entity.BookInfo;
 import com.baomidou.mybatisplus.extension.service.IService;
 
@@ -14,4 +17,5 @@ import com.baomidou.mybatisplus.extension.service.IService;
 // IService是mybatisplus提供的 基础服务接口
 public interface IBookInfoService extends IService<BookInfo> {
 
+    PageRespDto<BookInfoRespDto> searchBooks(BookSearchReqDto bookSearchReqDto);
 }

+ 42 - 0
novel-demo/src/main/java/com/sf/service/impl/BookInfoServiceImpl.java

@@ -1,11 +1,20 @@
 package com.sf.service.impl;
 
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.sf.dto.req.BookSearchReqDto;
+import com.sf.dto.resp.BookInfoRespDto;
+import com.sf.dto.resp.PageRespDto;
 import com.sf.entity.BookInfo;
 import com.sf.mapper.BookInfoMapper;
 import com.sf.service.IBookInfoService;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
+import java.util.List;
+
 /**
  * <p>
  * 小说信息 服务实现类
@@ -19,4 +28,37 @@ import org.springframework.stereotype.Service;
 public class BookInfoServiceImpl extends ServiceImpl<BookInfoMapper, BookInfo>
         implements IBookInfoService {
 
+    @Autowired
+    private BookInfoMapper bookInfoMapper;
+
+    // 分页的本质是limit  select * from book_info
+    @Override
+    public PageRespDto<BookInfoRespDto> searchBooks(BookSearchReqDto bookSearchReqDto) {
+        Page<BookInfo> page = new Page<>();
+        page.setCurrent(bookSearchReqDto.getPageNum());
+        page.setSize(bookSearchReqDto.getPageSize());
+
+        // 可以只使用mybatis plus来拼接
+//        LambdaQueryWrapper<BookInfo> wrapper = new LambdaQueryWrapper<>();
+//        if(!bookSearchReqDto.getKeyword().isBlank()){
+//            // book_name = 'keyword'
+//            wrapper.eq(BookInfo::getBookName,bookSearchReqDto.getKeyword());
+//        }
+//        if(bookSearchReqDto.getCategoryId() != null ){
+//            // and categoryId = 'categoryId'
+//            wrapper.eq(BookInfo::getCategoryId,bookSearchReqDto.getCategoryId());
+//        }
+//        bookInfoMapper.selectPage(page,wrapper);
+
+        // 还可以使用mybatis自身的sql语句来实现
+        List<BookInfo> bookInfos = bookInfoMapper.searchBooks(page, bookSearchReqDto);
+        List<BookInfoRespDto> bookInfoRespDtos = bookInfos.stream().map(bookInfo -> {
+            BookInfoRespDto bookInfoRespDto = new BookInfoRespDto();
+            BeanUtils.copyProperties(bookInfo, bookInfoRespDto);
+            return bookInfoRespDto;
+        }).toList();
+        PageRespDto<BookInfoRespDto> pageRespDto = PageRespDto.of(
+                bookSearchReqDto.getPageNum(), bookSearchReqDto.getPageSize(), 0, bookInfoRespDtos);
+        return pageRespDto;
+    }
 }

+ 4 - 2
novel-demo/src/main/java/com/sf/service/impl/NewsContentServiceImpl.java

@@ -29,10 +29,12 @@ public class NewsContentServiceImpl extends ServiceImpl<NewsContentMapper, NewsC
 
     @Override
     public NewsInfoRespDto getNews(Long id) {
+        // select * from news_info where id = '1';
         NewsInfo newsInfo = newsInfoMapper.selectById(id);
+        // select * from news_content where id = '1' limit 1;
         LambdaQueryWrapper<NewsContent> queryWrapper = new LambdaQueryWrapper<>();
-        queryWrapper.eq(NewsContent::getId, id)
-                .last("limit 1");
+        // eq = equals 等于
+        queryWrapper.eq(NewsContent::getId, id).last("limit 1");
         NewsContent newsContent = newsContentMapper.selectOne(queryWrapper);
         return NewsInfoRespDto.builder()
                 .title(newsInfo.getTitle())

+ 11 - 0
novel-demo/src/main/java/com/sf/service/impl/NewsInfoServiceImpl.java

@@ -10,6 +10,7 @@ import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -29,11 +30,21 @@ public class NewsInfoServiceImpl extends ServiceImpl<NewsInfoMapper, NewsInfo> i
     @Override
     public List<NewsInfoRespDto> listLatestNews() {
         // 从新闻信息表中查询出最新发布的两条新闻
+        // select * from news_info order by create_time desc limit 2;
         LambdaQueryWrapper<NewsInfo> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.orderByDesc(NewsInfo::getCreateTime).last("limit 2");
         List<NewsInfo> newsInfos = newsInfoMapper.selectList(queryWrapper);
         // map是映射处理 将list中每个newsInfo对象转换为NewsInfoRespDto对象
         // toList是将stream流的处理结果接收为list
+
+        // 翻译一下stream
+//        List<NewsInfoRespDto> newsInfoRespDtos = new ArrayList<>();
+//        for (NewsInfo newsInfo : newsInfos) {
+//            NewsInfoRespDto newsInfoRespDto = NewsInfoRespDto.builder().build();
+//            BeanUtils.copyProperties(newsInfo, newsInfoRespDto);
+//            newsInfoRespDtos.add(newsInfoRespDto);
+//        }
+
         return newsInfos.stream().map(newsInfo -> {
             NewsInfoRespDto newsInfoRespDto = NewsInfoRespDto.builder().build();
             BeanUtils.copyProperties(newsInfo, newsInfoRespDto);

+ 14 - 0
novel-demo/src/main/resources/mapper/BookInfoMapper.xml

@@ -2,4 +2,18 @@
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.sf.mapper.BookInfoMapper">
 
+    <select id="searchBooks" resultType="com.sf.entity.BookInfo">
+        select *
+        from book_info
+        where word_count > 0
+        <if test="dto.workDirection != null">
+            and work_direction = #{dto.workDirection}
+        </if>
+        <if test="dto.wordCountMin != null">
+            and word_count > #{dto.wordCountMin}
+        </if>
+        <if test="dto.wordCountMax != null">
+            and word_count <![CDATA[ < ]]> #{dto.wordCountMax}
+        </if>
+    </select>
 </mapper>

+ 34 - 0
novel-demo/src/test/java/com/sf/NovelDemoApplicationTests.java

@@ -2,7 +2,10 @@ package com.sf;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.sf.config.CorsProperties;
+import com.sf.dto.req.BookSearchReqDto;
 import com.sf.entity.BookInfo;
 import com.sf.mapper.BookInfoMapper;
 import com.sf.service.IBookInfoService;
@@ -69,4 +72,35 @@ class NovelDemoApplicationTests {
         System.out.println(corsProperties);
     }
 
+
+    @Test
+    public void test2(){
+//        IPage<BookInfo> page = new Page<>(1,10);
+        IPage<BookInfo> page = new Page<>();
+        // 当前页数  页面大小
+        page.setCurrent(1);
+        page.setSize(10);
+
+        QueryWrapper<BookInfo> queryWrapper = new QueryWrapper();
+//        queryWrapper.last("limit 10");
+        IPage<BookInfo> selectPage = bookInfoMapper.selectPage(page, queryWrapper);
+        List<BookInfo> records = selectPage.getRecords();
+        System.out.println(records);
+    }
+
+
+    @Test
+    public void test3(){
+//        IPage<BookInfo> page = new Page<>(1,10);
+        IPage<BookInfo> page = new Page<>();
+        // 当前页数  页面大小
+        page.setCurrent(1);
+        page.setSize(10);
+
+        BookSearchReqDto reqDto = BookSearchReqDto.builder()
+                .wordCountMin(300000).wordCountMax(500000).build();
+        List<BookInfo> bookInfos = bookInfoMapper.searchBooks(page, reqDto);
+        System.out.println(bookInfos);
+    }
+
 }