yblog(三)


阶段三

用代码编辑器创建所需的所有东西

// 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("about","collection","comment","link","type");
        strategy.setNaming(NamingStrategy.underline_to_camel);

分类模块编写

  • 想解决一个路径匹配不了的问题,在前面我们在pom文件中已经写了build的东西,那么接下来还要补充一个东西才能够自定义mapper生效。
#配置mapper xml文件的路径
mybatis-plus.mapper-locations=classpath:com/yhg/mainservice/mapper/xml/*.xml

不然会出现绑定不了数据的情况。!
就会出现这个问题:

Invalid bound statement (not found): com.yhg.mainservice.mapper.TypeMapper.getByName

controller:

    @PostMapping("save")
    public R save(@RequestBody Type type){
        typeService.saveType(type);
        return R.ok();
    }

1、在impl中如果正常写个方法是这样子的,

   @Autowired
    private TypeMapper typeMapper;

    //添加分类
    @Override
    public void saveType(Type type) {
        //查询分类是否存在
        Type t = typeMapper.getByName(type.getTypeName());

        if (t != null){
            throw new YHGException(20001,"该分类已存在!");
        }else {
            typeMapper.insert(type);
        }

    }

mapper:

    //添加分类
    Type getByName(@Param("typeName") String typeName);

xml:

<!--查询分类-->
    <select id="getByName" resultType="com.yhg.mainservice.entity.Type">
        select * from type where type_name = #{typeName}
    </select>

法二:使用baseMapper
mapper:

//添加分类
    public Type getByName(String typeName);

xml:

<!--查询分类-->
    <select id="getByName" resultType="com.yhg.mainservice.entity.Type">
        select * from type where type_name = #{typeName}
    </select>

impl:

    //添加分类
    @Override
    public void saveType(Type type) {
        //查询分类是否存在
        Type t = baseMapper.getByName(type.getTypeName());

        if (t != null){
            throw new YHGException(20001,"该分类已存在!");
        }else {
            baseMapper.insert(type);
        }
    }

typeController:

package com.yhg.mainservice.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhg.commonutils.R;
import com.yhg.mainservice.entity.Type;
import com.yhg.mainservice.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 帖子类型表 前端控制器
 * </p>
 *
 * @author 雨落弦鸣
 * @since 2020-05-25
 */
@RestController
@RequestMapping("/mainservice/type")
public class TypeController {
    @Autowired
    private TypeService typeService;

//添加分类
    @PostMapping("save")
    public R save(@RequestBody Type type){
        typeService.saveType(type);
        return R.ok();
    }

    //后台查询分类列表
    @GetMapping("findAll")
    public R findAll(){
        typeService.list(null);
        return R.ok();
    }
    //前台查询分类列表
    @GetMapping("findFront")
    public R findFront(){
        List<Type> list = typeService.list(new QueryWrapper<Type>()
                .ne("is_deleted", 1)
                .select("type_id", "type_name", "type_blog_count")
        );
        return R.ok().data("items",list);
    }
    //更新分类
    @PostMapping("update")
    public R update(@RequestBody Type type){
        typeService.updateById(type);
        return R.ok().message("更新成功!");
    }
    //根据id启用或者弃用
    @PostMapping("enable/{id}")
    public R enable(@PathVariable String id){
        typeService.enableById(id);
        return R.ok().message("更改成功!");
    }
    //根据id删除分类
    @DeleteMapping("{typeId}")
    public R delete(@PathVariable String typeId){
        typeService.removeById(typeId);
        return R.ok();
    }
}

Typeimpl:

package com.yhg.mainservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhg.mainservice.entity.Type;
import com.yhg.mainservice.mapper.TypeMapper;
import com.yhg.mainservice.service.TypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhg.servicebase.exceptionhandler.YHGException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 帖子类型表 服务实现类
 * </p>
 *
 * @author 雨落弦鸣
 * @since 2020-05-25
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {


    //添加分类
    @Override
    public void saveType(Type type) {
        //1、判断表里是否有同名
        //取出数据
        Type t = baseMapper.getByName(type.getTypeName());
        //判断条件
        if(t != null){
            throw new YHGException(20001,"该分类已存在!");
        }else {
            //插入数据
            baseMapper.insert(type);
        }
    }
//根据id启用或者弃用
    @Override
    public void enableById(String id) {
        Type type = baseMapper.selectById(id);
        if (type.getEnable() == 0){
            type.setEnable(1);
            baseMapper.updateById(type);
        }else {
            type.setEnable(0);
            baseMapper.updateById(type);
        }
    }

}

mpConfig:

package com.yhg.mainservice.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.yhg.mainservice.mapper")
public class MyBatisPlusConfig {
    /**
     * 逻辑删除插件
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
    /**
     * 乐观锁插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

Linkentity:

    @TableField(fill = FieldFill.INSERT)
    @ApiModelProperty(value = "创建时间", example = "2019-01-01 8:00:00")
    private Date gmtCreate;

    @ApiModelProperty(value = "更新时间", example = "2019-01-01 8:00:00")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;

    @ApiModelProperty(value = "乐观锁")
    @Version
    private Integer version;

    @ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
    @TableLogic
    private Boolean isDeleted;

自定义实现类 MyMetaObjectHandler:

package com.yhg.servicebase.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //属性名称,不是字段名称
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
}

LinkControntllar:

package com.yhg.mainservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhg.commonutils.R;
import com.yhg.mainservice.entity.Link;
import com.yhg.mainservice.entity.vo.LinkQuery;
import com.yhg.mainservice.service.LinkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 友情链接表 前端控制器
 * </p>
 *
 * @author 雨落弦鸣
 * @since 2020-05-25
 */

@RestController
@RequestMapping("/mainservice/link")
@Api(description = "友链管理")
public class LinkController {
    @Autowired
    private LinkService linkService;
    //保存友链
    @PostMapping("save")
    public R save(@RequestBody Link link){
        linkService.save(link);
        return R.ok().message("添加成功!");
    }
    //更新友链
    @PostMapping("update")
    public R update(@RequestBody Link link){
        boolean flag = linkService.updateById(link);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }
    //根据id获取
    @ApiOperation(value = "所有友链列表")
    @GetMapping("getLink/{id}")
    public R getLink(@ApiParam(name = "id", value = "友链ID", required = true)@PathVariable String id){
        Link link = linkService.getById(id);
        return R.ok().data("lists",link);
    }
    //逻辑删除友链的方法
    @DeleteMapping("{id}")
    public R removeLink(@PathVariable String id){
        boolean flag = linkService.removeById(id);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }
    //分页查询友链的方法
    @GetMapping("pageLink/{current}/{limit}")
    public R pageListLink(@PathVariable long current,
                          @PathVariable long limit){
        //创建page对象
        Page<Link> pageLink = new Page<>(current,limit);
        //调用方法实现分类
        //调用方法的时候,底层封装,把分页所有数据封装到pageLink对象里面
        linkService.page(pageLink,null);
        long total = pageLink.getTotal();//总记录数量
        List<Link> records = pageLink.getRecords();
        return R.ok().data("total",total).data("rows",records);
    }
    //条件查询带分页的方法
    @PostMapping("pageLinkCondition/{current}/{limit}")
    public R pageLinkCondition(@PathVariable long current, @PathVariable long limit,
                               @RequestBody(required = false) LinkQuery linkQuery){
        //创建page对象
        Page<Link> pageLink = new Page<>(current, limit);
        //构建条件
        QueryWrapper<Link> wrapper = new QueryWrapper<>();
        //多条件组合查询
        //mybatis 动态sql
        //判断条件值是否为空,如果不为空拼接条件
        String linkName = linkQuery.getLinkName();
        String begin = linkQuery.getBegin();
        String end = linkQuery.getEnd();

        if (!StringUtils.isEmpty(linkName)){
            wrapper.like("link_name",linkName);
        }
        if (!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create", begin);
        }

        if (!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create", end);
        }
        //排序
        wrapper.orderByDesc("gmt_create");

        //wrapper
        //调用方法实现条件查询分页

        linkService.page(pageLink,wrapper);
        long total = pageLink.getTotal();//总记录数
        List<Link> records = pageLink.getRecords();//数据list集合
        return R.ok().data("total",total).data("rows",records);
    }
    //


}

LInkQuery:

package com.yhg.mainservice.entity.vo;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class LinkQuery {

    @ApiModelProperty(value = "名称")
    private String linkName;

    @ApiModelProperty(value = "查询开始时间", example = "2019-01-01 10:10:10")
    private String begin;//注意,这里使用的是String类型,前端传过来的数据无需进行类型转换

    @ApiModelProperty(value = "查询结束时间", example = "2019-12-01 10:10:10")
    private String end;
}

BlogVo:

package com.yhg.mainservice.entity.vo;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.yhg.mainservice.entity.Type;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Date;

@Data
public class BlogVo {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "帖子id")
    @TableId(value = "blog_id", type = IdType.ID_WORKER_STR)
    private String blogId;

    @ApiModelProperty(value = "标题")
    private String blogTitle;

    @ApiModelProperty(value = "封面")
    private String blogImage;

    @ApiModelProperty(value = "帖子内容")
    private String blogContent;

    @ApiModelProperty(value = "点赞数")
    private Integer blogGoods;

    @ApiModelProperty(value = "阅读数")
    private Integer blogRead;

    @ApiModelProperty(value = "收藏数")
    private Integer blogCollection;

    @ApiModelProperty(value = "博客分类")
    private Type type;

    @ApiModelProperty(value = "简介")
    private String blogRemark;

    @ApiModelProperty(value = "评论数")
    private Integer blogComment;

    @TableField(fill = FieldFill.INSERT)
    @ApiModelProperty(value = "创建时间", example = "2019-01-01 8:00:00")
    private Date gmtCreate;

    @ApiModelProperty(value = "更新时间", example = "2019-01-01 8:00:00")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;

}

BlogServiceImpl:

package com.yhg.mainservice.service.impl;

import com.yhg.mainservice.entity.Blog;
import com.yhg.mainservice.entity.Type;
import com.yhg.mainservice.entity.vo.BlogVo;
import com.yhg.mainservice.mapper.BlogMapper;
import com.yhg.mainservice.mapper.TypeMapper;
import com.yhg.mainservice.service.BlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhg.servicebase.exceptionhandler.YHGException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * <p>
 * 博客表 服务实现类
 * </p>
 *
 * @author 雨落弦鸣
 * @since 2020-05-20
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {

    @Autowired
    private TypeMapper typeMapper;

    @Override
    @Transactional(rollbackFor = YHGException.class)
    public BlogVo readById(String id) {
        Blog blog = baseMapper.selectById(id);
        //没阅读查询一次,需要更新阅读数量
        blog.setBlogRead(blog.getBlogRead()+1);
        baseMapper.updateById(blog);
        //将blog转为blogVo
        BlogVo blogVo = new BlogVo();
        BeanUtils.copyProperties(blog,blogVo);
        //查询分类
        Type type = typeMapper.selectById(blog.getBlogType());
        blogVo.setType(type);
        return blogVo;
    }
}

文章作者: 寒光君
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 寒光君 !
 本篇
yblog(三) yblog(三)
阶段三用代码编辑器创建所需的所有东西// 5、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("about",
2020-05-26 寒光君
下一篇 
yblog(一) yblog(一)
yblog项目启动 摘要: 1、本次给大家带来的是SpringBoot+SpringCloud+Vue前后端分离开发的分布式、微服务、博客项目,致力于使广大网友尽可能通过这一个项目学到尽可能多的知识,使用当下最流行的技术以及第三方框架组件。
2020-05-20 寒光君
  目录