springboot整合MybatisPlus入门

SpringBoot集成MybatisPlus

1.导入依赖

<dependencies>
	<!--mybatisplus相关包 -->
    <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>

2.添加配置文件

resourse创建templates文件夹,添加模板文件。templates需要写对,后文的配置中有使用到。

2.1 模板文件添加

controller.java.vm

package ${
    
    package.Controller};

import ${
    
    package.Service}.${
    
    table.serviceName};
import ${
    
    package.Entity}.${
    
    entity};
import cn.westwei.query.${
    
    entity}Query;
import cn.westwei.util.AjaxResult;
import cn.westwei.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;

    /**
    * 保存和修改
    */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public AjaxResult save(@RequestBody ${
    
    entity} ${
    
    table.entityPath}){
    
    
        if(${
    
    table.entityPath}.getId()!=null){
    
    
            ${
    
    table.entityPath}Service.updateById(${
    
    table.entityPath});
        }else{
    
    
            ${
    
    table.entityPath}Service.insert(${
    
    table.entityPath});
        }
        return AjaxResult.me();
    }

    /**
    * 删除对象
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Long id){
    
    
        ${
    
    table.entityPath}Service.deleteById(id);
        return AjaxResult.me();
    }

   /**
   * 根据ID获取对象
   */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public AjaxResult get(@PathVariable("id")Long id){
    
    
        return AjaxResult.me().setResultObj(${
    
    table.entityPath}Service.selectById(id));
    }


    /**
    * 获取所有对象
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public AjaxResult list(){
    
    
        return AjaxResult.me().setResultObj(${
    
    table.entityPath}Service.selectList(null));
    }

    /**
    * 分页查询数据
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public AjaxResult json(@RequestBody ${
    
    entity}Query query){
    
    
        Page<${
    
    entity}> page = new Page<${
    
    entity}>(query.getPage(),query.getRows());
        page = ${
    
    table.entityPath}Service.selectPage(page);
        PageList pageList = new PageList<${
    
    entity}>(page.getTotal(),page.getRecords());
        return AjaxResult.me().setResultObj(pageList);
    }
}

query.java.vm

package cn.westwei.query;
/**
 *
 * @author ${author}
 * @since ${date}
 */
public class ${
    
    table.entityName}Query extends BaseQuery{
    
    
}

2.2 详细命名配置文件

在resource文件夹中添加详细的代码输出路径等文件。需要修改其中的路径为自己代码中的路径,修改部分参数

xxx.properties,配置文件名字可自己定义,后面代码生成的时候会使用。

#代码输出基本路径,一般选到java就可以了
OutputDir=E:/ideaworkspace/xxx/src/main/java

#mapper.xml SQL映射文件目录,一般选到resources就可以了
OutputDirXml=E:/ideaworkspace/xxx/src/main/resources

#domain的输出路径,一般选到java就可以了
OutputDirBase=E:/ideaworkspace/xxxx/src/main/java

#设置作者
author=westwei
#自定义包路径 java目录后的包路径,可自己定义
parent=cn.westwei

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
#数据库名
jdbc.url=jdbc:mysql:///xxx
#用户名
jdbc.user=root
#密码
jdbc.pwd=root

3.代码生成

3.1 生成工具Util

拷贝代码生成工具之后,修改Mybatis-Plus.properties文件名字为自己命名的。将自己数据库中需要生成的代码的表写在代码中设置表的地方。

文件中/cn/westwei/controller,/cn/westwei/domain等路径可以根据实际情况修改为自己的路径。

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.*;

/**
 * 生成代码的主类
 */
public class GenteratorCode {
    
    

    public static void main(String[] args) throws InterruptedException {
    
    
        //用来获取Mybatis-Plus.properties文件的配置信息
        ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-config-user"); //不要加后缀
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        gc.setFileOverride(false);
        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);// 表名生成策略
		// 表的设置,将数据库中需要生成基础CRUD的表拷贝到这个地方
        strategy.setInclude(new String[]{
    
    
                "t_xxx_address",
                "t_xxx_base",
                "t_xxx_real_info",
                "t_xxx_user"
        }); // 需要生成的表

        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent"));  //cn.westwei
        pc.setController("controller"); //cn.westweicontroller
        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>();

        //controller的输出配置
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
    
    
            @Override
            public String outputFile(TableInfo tableInfo) {
    
    
                //合并好的内容输出到哪儿?
                return rb.getString("OutputDir") + "/cn/westwei/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });
        //query的输出配置
        focList.add(new FileOutConfig("/templates/query.java.vm") {
    
    
            @Override
            public String outputFile(TableInfo tableInfo) {
    
    
                return rb.getString("OutputDirBase") + "/cn/westwei/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });

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

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
    
    
            @Override
            public String outputFile(TableInfo tableInfo) {
    
    
                return rb.getString("OutputDirXml") + "/cn/westwei/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.setMapper("/templates/mapper.java.vm");
        tc.setEntity(null);
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

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

3.2 生成目录结构

启动代码生成后。目录结构如下:

image-20211212113910283

3.3 MybatisPlus作用

mybatisplus功能比较强大,已经帮我们生成了基本的的CRUD。但是一些复杂的查询还是需要自己去完成。

这里只是简单的对MybatisPlus的集成初体验,详细的对基本CRUD使用以及高阶的操作,敬请期待。

Guess you like

Origin blog.csdn.net/qq_42859722/article/details/121885903