SpringBoot(8) 整合MyBatis-Plus代码生成器

简介:

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

具体可看MyBatis-Plus官网:https://mp.baomidou.com/

【MyBatis-Plus入门】springboot项目整合代码生成器

项目整体结构如下:

1.创建spring boot项目:

pom文件 - springboot版本约束:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <springboot.version>2.0.5.RELEASE</springboot.version>
</properties>
<!--约束springboot版本-->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${springboot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2.新建模块 

①导入依赖:

<dependencies>
    <!--springboot支持-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!--mybatis-plus支持-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <!--数据库支持-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

②配置:

spring:
  application:
    name: mct
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
mybatis-plus:
  mapper-locations: classpath:com/zhengqing/aigou/mapper/*Mapper.xml
  type-aliases-package: com.zhengqing.aigou.domain,com.zhengqing.aigou.query

③分页插件配置:

//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.zhengqing.aigou.mapper")
public class MybatisPlusConfig {
    @Bean  //分页插件
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

④入口类:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

3.新建模块 - 代码生成 

注:可以重新创建一个项目,也可以就在原来项目里面     -->  为了不影响运行的代码这里重新创建项目

①导入依赖:

<dependencies>
    <!--springboot支持-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!--mybatis-plus支持-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <!--模板引擎-->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.0</version>
    </dependency>
    <!--数据库支持-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

②配置:

#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=E:\\IdeaProjects\\IT_zhengqing\\MyBatisPlus_parent\\mp_code_test\\src\\main\\java
#mapper.xml SQL映射文件目录
OutputDirXml=E:\\IdeaProjects\\IT_zhengqing\\MyBatisPlus_parent\\mp_code_test\\src\\main\\resources

OutputDirBase=E:\\IdeaProjects\\IT_zhengqing\\MyBatisPlus_parent\\mp_code_test\\src\\main\\java
#设置作者
author=zhengqing
#自定义包路径
parent=com.zhengqing.aigou

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.user=root
jdbc.pwd=root

package com.zhengqing.aigou.client;

import ${package.Entity}.${entity};
import com.zhengqing.aigou.query.${entity}Query;
import com.zhengqing.aigou.util.AjaxResult;
import com.zhengqing.aigou.util.PageList;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@FeignClient(value = "AIGOU-ZUUL-GATEWAY",configuration = FeignClientsConfiguration.class,
        fallbackFactory = ${entity}ClientHystrixFallbackFactory.class)
@RequestMapping("/product/${table.entityPath}")
public interface ${entity}Client {
    /**
     * 保存和修改公用的
     * @param ${table.entityPath}  传递的实体
     * @return Ajaxresult转换结果
     */
    @RequestMapping(value="/add",method= RequestMethod.POST)
    AjaxResult save(${entity} ${table.entityPath});

    /**
     * 删除对象信息
     * @param id
     * @return
     */
    @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
    AjaxResult delete(@PathVariable("id") Integer id);

    //获取用户
    @RequestMapping("/{id}")
    ${entity} get(@RequestParam(value="id",required=true) Long id);


    /**
     * 查看所有的员工信息
     * @return
     */
    @RequestMapping("/list")
    public List<${entity}> list();

    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @RequestMapping(value = "/json",method = RequestMethod.POST)
    PageList<${entity}> json(@RequestBody ${entity}Query query);
}
package com.zhengqing.aigou.client;

import ${package.Entity}.${entity};
import com.zhengqing.aigou.query.${entity}Query;
import com.zhengqing.aigou.util.AjaxResult;
import com.zhengqing.aigou.util.PageList;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 郑清
 * @date 2019/01/12-20:56
 */
@Component
public class ${entity}ClientHystrixFallbackFactory implements FallbackFactory<${entity}Client> {

    @Override
    public ${entity}Client create(Throwable throwable) {
        return new ${entity}Client() {
            @Override
            public AjaxResult save(${entity} ${table.entityPath}) {
                return null;
            }

            @Override
            public AjaxResult delete(Integer id) {
                return null;
            }

            @Override
            public ${entity} get(Long id) {
                return null;
            }

            @Override
            public List<${entity}> list() {
                return null;
            }

            @Override
            public PageList<${entity}> json(${entity}Query query) {
                return null;
            }
        };
    }
}
package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.zhengqing.aigou.query.${entity}Query;
import com.zhengqing.aigou.util.AjaxResult;
import com.zhengqing.aigou.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    /**
    * 保存和修改公用的
    * @param ${table.entityPath}  传递的实体
    * @return Ajaxresult转换结果
    */
    @RequestMapping(value="/add",method= RequestMethod.POST)
    public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
        try {
            if(${table.entityPath}.getId()!=null){
                ${table.entityPath}Service.updateById(${table.entityPath});
            }else{
                ${table.entityPath}Service.insert(${table.entityPath});
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败!"+e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Integer id){
        try {
            ${table.entityPath}Service.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败!"+e.getMessage());
        }
    }

    //获取用户
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ${entity} get(@RequestParam(value="id",required=true) Long id)
    {
        return ${table.entityPath}Service.selectById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<${entity}> list(){

        return ${table.entityPath}Service.selectList(null);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @RequestMapping(value = "/json",method = RequestMethod.POST)
    public PageList<${entity}> json(@RequestBody ${entity}Query query)
    {
        Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
            page = ${table.entityPath}Service.selectPage(page);
            return new PageList<${entity}>(page.getTotal(),page.getRecords());
    }
}
package com.zhengqing.aigou.query;


/**
 *
 * @author ${author}
 * @since ${date}
 */
public class ${table.entityName}Query extends BaseQuery{
}

③代码生成器: 

public class GenteratorCode {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        ResourceBundle rb = ResourceBundle.getBundle("gen");
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor(rb.getString("author"));
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(rb.getString("jdbc.driver"));
        dsc.setUsername(rb.getString("jdbc.user"));
        dsc.setPassword(rb.getString("jdbc.pwd"));
        dsc.setUrl(rb.getString("jdbc.url"));
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 t_user_xxx UserXxx
        strategy.setInclude(new String[]{"t_user"}); // 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("domain");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };

        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

        // 调整 domain 生成目录演示
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/com/zhengqing/aigou/domain/" + tableInfo.getEntityName() + ".java";
            }
        });

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/com/zhengqing/aigou/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService("/templates/service.java.vm");
        tc.setServiceImpl("/templates/serviceImpl.java.vm");
        tc.setEntity(null);
        tc.setMapper("/templates/mapper.java.vm");
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();
    }

}

④:运行生成文件

4.测试CRUD:

//测试:增删改查+高级查询
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MPTest {
    @Autowired
    private IUserService userService;

    @Test
    public void testAdd() throws Exception {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                User user = new User();
                user.setName("zz-" + i);
                userService.insert(user);
            } else {
                User user = new User();
                user.setName("qq-" + i);
                userService.insert(user);
            }
        }
    }

    @Test
    public void testDelete() throws Exception {
        userService.deleteById(1L);
    }

    @Test
    public void testUpdate() throws Exception {
        User user = userService.selectById(35L);
        user.setName("修改了...");
        userService.updateById(user);
        user = userService.selectById(35L);
        System.out.println(user);
    }

    @Test
    public void testQuery() throws Exception {
        List<User> users = userService.selectList(null);
        System.out.println(users);
    }

    @Test //高级查询
    public void testQueryAndPage() throws Exception {
        Page<User> page = new Page<>(1, 10); //参数1:当前页  参数2:每页显示多少条数据
        Wrapper wrapper = new EntityWrapper();
        wrapper.like("name", "z");
        userService.selectPage(page, wrapper);
        System.out.println("总数:" + page.getTotal());
        System.out.println(page.getRecords());
    }
}

最后附上项目源码:https://pan.baidu.com/s/1F-Pkrol-A4h0Q4u7HTBB1A

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值