MyBatisPlus

本文介绍了MyBatisPlus的基础知识和使用步骤,包括如何在项目中添加依赖、创建实体类和Mapper接口,以及配置扫描和数据源。通过CodeGenerator类展示了MyBatisPlus的代码生成器功能,自动生成实体类、Mapper接口和Mapper XML文件。此外,还探讨了MyBatisPlus简化开发、提供代码生成器等优势。
摘要由CSDN通过智能技术生成

壹.MyBatisPlus

一.什么是MyBatisPlus

1.就是在MyBatis框架的基础上延伸了一些新的功能的框架

2.使用MyBatisPlus不用再导入Mybatis的依赖了

二.为什么要用MyBatisPlus

1.就是MyBatisPlus增加了更多功能,方便我们处理数据

三.怎么使用MyBatisPlus

1.找到父项目的pom.xml文件添加2个

​ 1.1 新增版本依赖代码

	<properties>
        <java.version>1.8</java.version>
        <!--加入的myBatisPlus一个版本依赖-->
        <mybatis.plus.version>3.3.1</mybatis.plus.version>
    </properties>

​ 1.2 新增myBatisPlus的依赖管理代码

 <!--加入的myBatisPlus的依赖管理-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis.plus.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-extension</artifactId>
                <version>${mybatis.plus.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>${mybatis.plus.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.找到子项目的pom.xml文件添加1个

​ 2.1 新增myBatisPlus的依赖管理代码

<!--子项目的pom.xml文件使用myBatisPlus的这些依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

四.MyBatisPlus使用体验

1.创建Tag实体类

​ 创建一个实体类使用MyBatisPlus

​ 创建Tag实体类代码如下

@Data
public class Tag {
    private Integer id;
    private String name;
    private String createby;//不能使用createBy命名,数据库会识别成create_by
    private String createtime;
}

2.创建mapper接口

​ 包中创建这个实体类对应的Mapper接口

​ TagMapper代码如下

//BaseMapper接口是MyBatisPlus提供的
//其中包含着一些最基本的查询
public interface TagMapper extends BaseMapper<Tag> {
    
}

3.扫描@MapperScan

​ 不要忘了在配置类中配置扫描@MapperScan

@SpringBootApplication
@MapperScan("cn.tedu.straw.portal.mapper")
public class StrawPortalApplication {
    public static void main(String[] args) {
        SpringApplication.run(StrawPortalApplication.class, args);//自动生成的这行代码
    }
}

4.配置application.properties

​ 配置application.properties(数据源配置)

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/straw?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root

#这句什么意思
logging.level.cn.tedu.straw.portal.mapper=trace

5.测试类测试

@Autowired(required = false)
    TagMapper tagMapper;

    @Test
    public void testTag(){
        Tag tag=tagMapper.selectById(14);
        System.out.println(tag);
    }

贰.MyBatisPlus的功能

一.简化实体类的mapper接口

1.MyBatisPlus能够帮助我们简化具体的实体类的mapper接口

2.BaseMapper接口是MyBatisPlus提供的
其中包含着一些最基本的查询

二.MyBatisPlus的代码生成器

MyBatisPlus能够按照数据库的内容(表,列等信息)自动生成实体类和实体类相关的其它类

这些功能是由MyBatisPlus的代码生成器提供的

1.导入依赖

​ 上面的已经将代码生成器需要的依赖导入了

2.准备使用

​ 因为我们要生成的代码需要一些配置,但是这些配置在代码生成后就不需要了

​ 所以我们单独创建一个子项目straw-generator完成这个操作

3.创建子项目straw-generator

​ 这是一个单纯的Springboot项目不需要勾选SpringWeb,配置如下:

3.1 勿忘父子相认
<modules>
    <父项目中:务忘父子相认-->
    <module>straw-generator</module>
</modules>


 <子项目中:务忘父子相认-->
<parent>
    <!--新增代码1:务忘父子相认-->
    <groupId>cn.tedu</groupId>
    <artifactId>straw</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
3.2 新建的子项目中添加2个依赖
<!--MybatisPlus代码生成器依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-extension</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!--lombok依赖-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
3.3 创建类CodeGenerator

​ 创建一个类CodeGenerator,

​ 类中复制从苍老师的网站获得代码生成器的代码,记得修改导入的包名,检查url中的数据库名和password,

package cn.tedu.generator;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
 * @Description: 代码生成类
 */
public class CodeGenerator {
    //数据库连接参数
    public static String driver = "com.mysql.cj.jdbc.Driver";
    public static String url = "jdbc:mysql://localhost:3306/straw?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
    public static String username="root";
    public static String password="root";
    //父级别包名称
    public static String parentPackage = "cn.tedu.straw";
    //代码生成的目标路径
    public static String generateTo = "/straw-generator/src/main/java";
    //mapper.xml的生成路径
    public static String mapperXmlPath = "/straw-generator/src/main/resources/mapper";
    //控制器的公共基类,用于抽象控制器的公共方法,null值表示没有父类
    public static String baseControllerClassName ;// = "cn.tedu.straw.portal.base.BaseController";
    //业务层的公共基类,用于抽象公共方法
    public static String baseServiceClassName ;   // = "cn.tedu.straw.portal.base.BaseServiceImpl";
    //作者名
    public static String author = "tedu.cn";
    //模块名称,用于组成包名
    public static String modelName = "portal";
    //Mapper接口的模板文件,不用写后缀 .ftl
    public static String mapperTempalte = "/ftl/mapper.java";

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    /**
     * RUN THIS
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + generateTo);
        gc.setAuthor(author);
        gc.setOpen(false);
        //设置时间类型为Date
        gc.setDateType(DateType.TIME_PACK);
        //开启swagger
        //gc.setSwagger2(true);
        //设置mapper.xml的resultMap
        gc.setBaseResultMap(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        // dsc.setSchemaName("public");
        dsc.setDriverName(driver);
        dsc.setUsername(username);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setEntity("model");
        //pc.setModuleName(scanner("模块名"));
        pc.setModuleName(modelName);
        pc.setParent(parentPackage);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + mapperXmlPath
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));
        mpg.setTemplate(new TemplateConfig().setMapper(mapperTempalte));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //字段驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //设置实体类的lombok
        strategy.setEntityLombokModel(true);
        //设置controller的父类
        if (baseControllerClassName!=null) strategy.setSuperControllerClass(baseControllerClassName);
        //设置服务类的父类
        if (baseServiceClassName !=null ) strategy.setSuperServiceImplClass(baseServiceClassName);
        // strategy.
        //设置实体类属性对应表字段的注解
        strategy.setEntityTableFieldAnnotationEnable(true);
        //设置表名
        String tableName = scanner("表名, all全部表");
        if(! "all".equalsIgnoreCase(tableName)){
            strategy.setInclude(tableName);
        }
        strategy.setTablePrefix(pc.getModuleName() + "_");
        strategy.setRestControllerStyle(true);
        mpg.setStrategy(strategy);

        // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
3.4 创建ftl文件夹

​ 在resources中创建ftl文件夹(Directory), 文件夹中创建mapper.java.ftl文件(File),

​ 复制如下代码到文件中

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.springframework.stereotype.Repository;

/**
 * <p>
 * ${table.comment!} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
@Repository
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
</#if>
3.5 运行main方法

​ 运行CodeGenerator类中的main方法

3.6 在控制台输入all

​ 输入all等待方法运行完毕,

​ 项目中就包含这些生成的类了!

3.7 四个生成的包到straw-portal

​ 把cn.tedu.straw.portal中生成的四个包,全选、复制到straw-portal子项目中,Overwrite覆盖

mybatisplus 依赖是指在项目中使用 MyBatis-Plus 框架所需要的相关依赖包。根据提供的引用内容,可以看出有多种方法引入 mybatisplus 依赖。 第一种方法,引用中列出了一系列的依赖包,包括了 jsqlparser-4.3.jar、mybatis-3.5.9.jar、mybatis-plus-3.5.1.jar 等等。这些依赖包需要手动下载并添加到项目的构建路径中,以保证项目能够正常使用 MyBatis-Plus 框架。 第二种方法,引用中给出了使用 Maven 构建项目时添加 mybatisplus 依赖的方法。在项目的 pom.xml 文件中,可以通过添加如下依赖来引入 mybatisplus: ```xml <!--Mybatis-plus的依赖--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency> <!--mysql的依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--lombok的依赖,为了优化实体类,可以不去实现实体类的set()、get()--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> ``` 第三种方法,引用中给出了另一种使用 Maven 构建项目时添加 mybatisplus 依赖的方法。在项目的 pom.xml 文件中,可以通过添加如下依赖来引入 mybatisplus: ```xml <!--mp依赖--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.3</version> </dependency> ``` 以上是三种常用的引入 mybatisplus 依赖的方法,根据实际情况选择适合自己项目的方法来引入 mybatisplus 依赖。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [mybatis-plus所有依赖包](https://download.csdn.net/download/tfstone/85322273)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [MyBatisPlus](https://blog.csdn.net/m0_60213304/article/details/124203155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [MyBatis-Plus](https://blog.csdn.net/weixin_43868299/article/details/110759287)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值