栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis-Plus 使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis-Plus 使用

简介

SpringBoot、Mysql、Mybatis-Plus

创建表

Mysql创建表

CREATE TABLE user
(
    id char(19) NOT NULL COMMENT '主键ID',
    name VARCHAr2(32) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAr(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);
创建maven项目

pom中添加



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.1.RELEASE
         
    

    com.yy.ascm
    ascm
    1.0-SNAPSHOT

    
        8
        8
        1.8
        3.0.5
        2.0
        2.7.0
    


    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis-plus.version}
        

        
        
            mysql
            mysql-connector-java
        

        
        
            org.apache.velocity
            velocity-engine-core
            ${velocity.version}
        

        
        
            io.springfox
            springfox-swagger2
            ${swagger.version}
        
        
        
            io.springfox
            springfox-swagger-ui
            ${swagger.version}
        

        
        
            org.projectlombok
            lombok
        
        
		
            junit
            junit
            4.12
        

    

    
    
        
            
                src/main/java
                
                    **
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(projectPath + "/src/main/java");
        gc.setAuthor("yayun");
        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://192.168.0.106:8306/ascm?serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        //com.yy.eduservice
        pc.setModuleName("ascm"); //模块名
        pc.setParent("com.yy");
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("script_call_db"); // 对应表名
        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();
    }
}

执行后生成对应文件夹及文件

返回工具类

接口

package com.yy.commonutils;

public interface ResultCode {

    public static Integer SUCCESS = 20000;

    public static Integer ERROR = 20001;
}

实现

package com.yy.commonutils;

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

import java.util.HashMap;
import java.util.Map;

@Data
public class R implements ResultCode {
    @ApiModelProperty(value = "是否成功")
    private Boolean success;

    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private Map data = new HashMap();

    private R(){}

    public static R ok(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }

//    返回R是,是返回了当前对象,方便链式使用
    public static R error(){
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }

    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public R data(Map map){
        this.setData(map);
        return this;
    }
}


编写Controller
@Api(value = "/", tags = "用户管理")
@RestController
@RequestMapping("/userservice")
@CrossOrigin
public class UserController {
	@Autowired
    private UserService userService;

	@ApiOperation(value = "分页查询所有用户")
    @GetMapping("getUserPage/{current}/{limit}")
    public R getUserPage(@PathVariable Long current,
                            @PathVariable Long limit){

        Page page = new Page<>(current, limit);
        userService.page(page,null);
        List records = page.getRecords();
        Long total = page.getTotal();
        return R.ok().data("records",records).data("total",total);

    }

	@ApiOperation(value = "获取所有用户")
    @GetMapping("getAllUser")
    public R getAllUser(){
        List list = userService.list(null);
        return R.ok().data("list",list);
    }
}
创建启动类
package com.yy.ascm;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ComponentScan(basePackages = {"com.yy"})
@MapperScan("com.yy.userservice.mapper")
public class AscmApplication {
    public static void main(String[] args) {
        SpringApplication.run(AscmApplication.class, args);
    }
}

测试

访问http://localhost:8001/swagger-ui.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/749592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号