SpringBoot2.2.1.RELEASE+MyBatis-Plus3.0.5使用教程

注解

逻辑删除

 @TableLogic
 private Integer isDeleted;

pom文件

	<parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.1.RELEASEversion>
        <relativePath/> 
    parent>
        
        <dependency>
            <groupId>org.apache.velocitygroupId>
            <artifactId>velocity-engine-coreartifactId>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
        dependency>
        
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
        dependency>
        
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
        dependency>
        
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>

插件

@Configuration
@EnableTransactionManagement
@MapperScan("com.shengun.eduservice.mapper")
public class MyBatisPlusConfig {

    /**
     * 逻辑删除插件
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }


}

自动注入

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //参数1:对应类中的属性名称
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
}

实操

mybatis-plus 逆向生成代码

package com.achang.eduservice;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

/**
 * @阿昌
 */
public class CodeGenerator {

    @Test
    public void run() {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir("F:\\Java\\idea-workpace\\guli-parent\\service\\service-edu" + "/src/main/java"); //输出目录

        gc.setAuthor("shengun"); //作者名
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖

        gc.setServiceName("%sService");	//去掉Service接口的首字母I
        gc.setIdType(IdType.ID_WORKER_STR); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();

        //生成包:com.achang.eduservice
        pc.setModuleName("eduservice"); //模块名
        pc.setParent("com.shengun");

        //生成包:com.achang.controller
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("edu_teacher");//根据数据库哪张表生成,有多张表就加逗号继续填写

        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);


        // 6、执行
        mpg.execute();
    }
}

注解

实体类

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="EduTeacher对象", description="讲师")
public class EduTeacher implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "讲师ID")
    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private String id;

    @ApiModelProperty(value = "讲师姓名")
    private String name;

    @ApiModelProperty(value = "讲师简介")
    private String intro;

    @ApiModelProperty(value = "讲师资历,一句话说明讲师")
    private String career;

    @ApiModelProperty(value = "头衔 1高级讲师 2首席讲师")
    private Integer level;

    @ApiModelProperty(value = "讲师头像")
    private String avatar;

    @ApiModelProperty(value = "排序")
    private Integer sort;

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

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    @ApiModelProperty(value = "更新时间")
    private Date gmtModified;
}

mapper

@Repository
public interface EduTeacherMapper extends BaseMapper<EduTeacher> {

}

mapper.xml


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shengun.eduservice.mapper.EduTeacherMapper">

mapper>

service

public interface EduTeacherService extends IService<EduTeacher> {
    public void pageQuery(Page<EduTeacher> pageParam, TeacherQuery teacherQuery);
}

serviceImpl

@Service
public class EduTeacherServiceImpl extends ServiceImpl<EduTeacherMapper, EduTeacher> implements EduTeacherService {

    @Autowired
    private EduTeacherMapper eduTeacherMapper;

    @Override
    public void pageQuery(Page<EduTeacher> pageParam, TeacherQuery teacherQuery) {
        //构建查询条件
        QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper<>();

        //取出值
        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();

        //判断条件是否为空,如果为空,就不拼接
        if(!StringUtils.isEmpty(name)){
            queryWrapper.like("name", name); // like
        }
        if(!StringUtils.isEmpty(level)){
            queryWrapper.eq("level", level);  //=
        }
        if(!StringUtils.isEmpty(begin)){
            queryWrapper.ge("gmt_create", begin); //>=
        }
        if(!StringUtils.isEmpty(end)){
            queryWrapper.le("gmt_modified", end); // <=
        }
        //带上查询条件分页查询
        eduTeacherMapper.selectPage(pageParam, queryWrapper);

    }
}

controller

package com.shengun.eduservice.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shengun.commonutils.R;
import com.shengun.eduservice.entity.EduTeacher;
import com.shengun.eduservice.entity.vo.TeacherQuery;
import com.shengun.eduservice.service.EduTeacherService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 

* 讲师 前端控制器 *

* 访问url: http://localhost:8001/eduservice/edu-teacher/xxxx * @author shengun * @since 2022-03-26 */
@RestController @RequestMapping("/eduservice/edu-teacher") @Slf4j @ApiModel(value="教师管理",description = "讲师管理") public class EduTeacherController { @Autowired private EduTeacherService eduTeacherService; /** * 查询讲师所有数据 * @return 所有讲师数据 */ @ApiOperation(value="所有讲师列表") @GetMapping("/findAll") public R list(){ List<EduTeacher> list = eduTeacherService.list(null); return R.ok().data("items", list); } /** * 根据ID删除讲师记录 * @param id 删除讲师ID * @return 是否成功删除讲师 */ @ApiOperation(value ="根据ID删除讲师") @DeleteMapping("/{id}") public R deleteTeacherById(@ApiParam(value="讲师ID") @PathVariable("id") String id) { log.info("##########获取要删除id值:" + id); return eduTeacherService.removeById(id) ? R.ok() : R.error(); } /** * 分页讲师列表 * @param current 当前页码 * @param limit 每页记录数 * @return 返回分页查询记录和总记录数 */ @GetMapping("/pageList/{current}/{limit}") @ApiOperation(value = "分页讲师列表") public R pageList(@ApiParam(name = "current", value = "当前页码", required = true) @PathVariable("current") Long current, @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable("limit") Long limit) { //查询分页 Page<EduTeacher> pageParam = new Page<>(current, limit); //分页查询,查完后,会将数据封装在pageParam中 eduTeacherService.page(pageParam, null); //获得记录数 List<EduTeacher> records = pageParam.getRecords(); //获取总记录数 long total = pageParam.getTotal(); return R.ok().data("total", total).data("rows", records); } /** * 多条件查询讲师带分页 GET方法 * @param current 当前页码 * @param limit 每页记录数 * @param teacherQuery 多条件 * @return 多条件查询的记录 */ @ApiOperation(value = "多条件查询讲师带分页GET") @GetMapping("/pageTeacherConditionGet/{current}/{limit}") public R pageTeacherConditionGet(@ApiParam(name = "current", value = "当前页码", required = true) @PathVariable("current") Long current, @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable("limit") Long limit, TeacherQuery teacherQuery){ Page<EduTeacher> pageParam = new Page<>(); eduTeacherService.pageQuery(pageParam, teacherQuery); //报错 int i = 10/0; //获取查询到的数据 List<EduTeacher> records = pageParam.getRecords(); //获取总记录数 long total = pageParam.getTotal(); return R.ok().data("total",total).data("rows",records); } /** * 多条件查询讲师带分页 POST方法 * @param current 当前页码 * @param limit 每页记录数 * @param teacherQuery 多条件 * @return 多条件查询的记录 json数据 */ @ApiOperation(value = "多条件查询讲师带分页POST") @PostMapping("/pageTeacherConditionPost/{current}/{limit}") public R pageTeacherConditionPost(@ApiParam(name = "current", value = "当前页码", required = true) @PathVariable("current") Long current, @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable("limit") Long limit, @RequestBody(required = false) TeacherQuery teacherQuery){ Page<EduTeacher> pageParam = new Page<>(); eduTeacherService.pageQuery(pageParam, teacherQuery); //获取查询到的数据 List<EduTeacher> records = pageParam.getRecords(); //获取总记录数 long total = pageParam.getTotal(); return R.ok().data("total",total).data("rows",records); } /** * 新增讲师 * @param eduTeacher 讲师jsOn * @return 返回是否成功新增结果 */ @ApiOperation(value="新增讲师") @PostMapping("/save") public R save(@RequestBody EduTeacher eduTeacher){ boolean save = eduTeacherService.save(eduTeacher); return save ? R.ok() : R.error(); } /** * 根据id查询记录 * @param id 教师id * @return 返回查询记录 */ @GetMapping("{id}") @ApiOperation(value="根据id查询") public R getById(@PathVariable("id") String id) { EduTeacher eduTeacher = eduTeacherService.getById(id); return R.ok().data("item", eduTeacher); } /** * 根据ID修改教师信息 * @param eduTeacher 教师json * @return 是否修改成功 */ @ApiOperation(value="根据ID修改教师信息") @PostMapping("/updateById") public R updateById(@RequestBody EduTeacher eduTeacher){ boolean flag = eduTeacherService.updateById(eduTeacher); return flag?R.ok():R.error(); } }

你可能感兴趣的:(Mybatis,vue.js,javascript,前端)