【第11章】SpringBoot实战篇之文章(下)含条件分页


前言

本章内容继续介绍文章,下面介绍

  • 文章列表查询
  • 文章查询
  • 文章更新
  • 文章删除
  • 文章列表查询(条件分页)

一、文章列表查询

1. ArticleController

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    @PostMapping
    /**
     * 文章列表查询
     * @return Result<List<Article>>
     */
    @GetMapping
    public Result<List<Article>> queryList(){
        List<Article> categories = articleService.selectList();
        return Result.success(categories);
    }
}

2. ArticleService

public interface ArticleService {
    public List<Article> selectList();
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Override
    public List<Article> selectList() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_user",userId);
        return articleMapper.selectList(queryWrapper);
    }
}

二 、文章查询

1. ArticleController

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    /**
     * 文章查询
     * @param id 编号
     * @return Article
     */
    @GetMapping("detail")
    public Result<Article> detail(Integer id){
        Article categories = articleService.selectOne(id);
        return Result.success(categories);
    }
}

2. ArticleService

public interface ArticleService {
    public Article selectOne(Integer id);
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Override
    public Article selectOne(Integer id) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        queryWrapper.eq("create_user",userId);
        return articleMapper.selectOne(queryWrapper);
    }
}

三、文章更新

1. ArticleController

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    /**
     * 文章更新
     * @param article 文章
     * @return Result
     */
    @PutMapping
    public Result update(@RequestBody @Validated(ValidatedGroups.Update.class) Article article){
        int i = articleService.update(article);
        if(i!=1){
            return Result.error("更新文章失败");
        }
        return Result.success("更新文章成功");
    }
}

2. ArticleService

public interface ArticleService {
    public int update(Article article);
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Override
    public int update(Article article) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        UpdateWrapper<Article> wrapper = new UpdateWrapper<>();
        wrapper.set("update_time",LocalDateTime.now());
        wrapper.eq("id",article.getId());
        wrapper.eq("create_user",userId);
        return articleMapper.update(article,wrapper);
    }
}

四、文章删除

1. ArticleController

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    /**
     * 文章删除
     * @param id 编号
     * @return Result
     */
    @DeleteMapping
    public Result delete(Integer id){
        int i = articleService.delete(id);
        if(i!=1){
            return Result.error("删除文章失败");
        }
        return Result.success("删除文章成功");
    }
}

2. ArticleService

public interface ArticleService {
    public int delete(Integer id);
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Override
    public int delete(Integer id) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        UpdateWrapper<Article> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("create_user",userId);
        return articleMapper.delete(wrapper);
    }
}

五、文章列表查询(条件分页)

这里有点技术含量,稍微介绍下,我们使用Mybatis-Plus提供的分页插件,参考这里

1.ArticleController

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    /**
     * 文章列表查询(条件分页)
     * @param pageNum 当前页
     * @param pageSize 页数
     * @param categoryId 分类id
     * @param state 发布状态
     * @return Result<ObjectMapper>
     */
    @GetMapping("/page")
    public Result<Map<String,Object>> selectPage(Integer pageNum, Integer pageSize, @RequestParam(required = false) Integer categoryId,@RequestParam(required = false) String state) throws JsonProcessingException {
        Page<Article> articlePage = articleService.selectPage(pageNum, pageSize, categoryId, state);
        Map<String,Object> map=new HashMap<>();
        map.put("total",articlePage.getTotal());
        map.put("items",articlePage.getRecords());
        return Result.success(map);
    }
}

2.ArticleService

public interface ArticleService {
    public Page<Article> selectPage(Integer current, Integer size, Integer categoryId, String state);
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    public Page<Article> selectPage(Integer current,Integer size,Integer categoryId,String state) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_user",userId);
        if(categoryId!=null){
            queryWrapper.eq("category_id",categoryId);
        }
        if(StringUtils.hasLength(state)){
            queryWrapper.eq("state",state);
        }
        Page<Article> articlePage = new Page<>(current,size);
        return articleMapper.selectPage(articlePage,queryWrapper);
    }
}

3. Article

@Getter
@Setter
@ToString
public class Article {
    @NotNull(message = "id不能为空",groups = {ValidatedGroups.Update.class})
    @TableId(type = IdType.AUTO)
    private Integer id;//主键ID
    @Pattern(regexp = "^\\S{1,10}$",message = "文章标题为1-10个字符")
    @NotEmpty(message = "文章标题不能为空")
    private String title;//文章标题
    @NotEmpty(message = "文章内容不能为空")
    private String content;//文章内容
    @Pattern(regexp = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$",message = "封面图像格式应为http链接")
    private String coverImg;//封面图像
    @ArticleState
    private String state;//发布状态 已发布|草稿
    private Integer categoryId;//文章分类id
    private Integer createUser;//创建人ID
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;//创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;//更新时间
}

4. MybatisPlusConfig

package org.example.springboot3.mybatisplus.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;

/**
 * Create by zjg on 2024/5/29
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }
}

5. sql

[2024-05-29 22:43:45.345][http-nio-8080-exec-5][DEBUG]- org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:135) - ==>  Preparing: SELECT id,title,content,cover_img,state,category_id,create_user,create_time,update_time FROM article WHERE (create_user = ? AND category_id = ? AND state = ?) LIMIT ?
[2024-05-29 22:43:45.345][http-nio-8080-exec-5][DEBUG]- org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:135) - ==> Parameters: 1(Integer), 2(Integer), 草稿(String), 3(Long)
[2024-05-29 22:43:45.348][http-nio-8080-exec-5][DEBUG]- org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:135) - <==      Total: 3

6. 结果

在这里插入图片描述


总结

回到顶部

最初的梦想,就像好好睡了一觉,直到天亮。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值