MyBatisPlus介绍

1.MyBatisPlus简单介绍

前面开发平台服务,由于都是原来操作的使用模拟实现,但是真实项目肯定要访问数据操作,并且每个domain都有crud,需多次写重复代码。我们使用MybatisPlus,就不用写重复代码,并且还有模板的功能,可以一键生成daomin,query,mapper接口,mapper.xml,service,controller,非常好用。

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变为简化开发、提高效率而生
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
就是mybatis的加强版,功能更强大

创建一个测试工程,工程下面创建两个测试模块
结构如下
在这里插入图片描述
顶级父pom.xml依赖导入

不需要cloud,因此不导入cloud的依赖

<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>

    <!--顶级父类,导入依赖的管理包-->
    <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.mp_generator

在这里插入图片描述
pom.xml

<dependencies>
        <!--代码生成器依赖-->
        <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>
        <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>

GenteratorCode

public class GenteratorCode {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        ResourceBundle rb = ResourceBundle.getBundle("mpconfig");
        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);// 表名生成策略
        strategy.setInclude(new String[]{"t_emp"}); // 需要生成的表
        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")+ "/cn/itsource/aigou/mp/domain/" + tableInfo.getEntityName() + ".java";
            }
        });

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/cn/itsource/aigou/mp/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();
    }

}

mpconfig.properties

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

#我们生产代码要放的项目的地址:
OutputDirBase=D:\\idea_work\\mp_parent\\mp_project\\src\\main\\java
#设置作者
author=lanca
#自定义包路径
parent=cn.itsource.aigou.mp

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

3.mp_project

pom.xml

<dependencies>
        <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>
        <!--baomidou的启动依赖-->
        <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>

在这里插入图片描述
application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///aigou_mp
    username: root
    password: 123456
mybatis-plus: #配置别名
  type-aliases-package: cn.itsource.aigou.mp.domain

IEmpServiceTest

@RunWith(SpringRunner.class)
@SpringBootTest
public class IEmpServiceTest {

    @Autowired
    private IEmpService empService;

    @Test
    public void testInsert() throws Exception{
        Emp emp = new Emp();
        emp.setName("张三");
        empService.insert(emp);
    }


    @Test
    public void testFor() throws Exception {
        for (int i = 0; i <17; i++) {
            Emp emp = new Emp();
            emp.setName("张三"+i);
            emp.setHobby("meinv"+i);
            empService.insert(emp);
        }
    }

    @Test
    public void testGetOneById() throws Exception {
        System.out.println(empService.selectById(50L));
    }

    @Test
    public void testSelectList() throws Exception {
        EntityWrapper<Emp> wrapper = new EntityWrapper<>();
        wrapper.eq("name", "张三3");
        List<Emp> emps = empService.selectList(wrapper);
        for (Emp emp : emps){
            System.out.println(emp);
        }
    }

    @Test
    public void testAll() throws Exception {
        EntityWrapper<Emp> wrapper = new EntityWrapper<>();
        List<Emp> emps = empService.selectList(wrapper);
        for (Emp emp : emps) {
            System.out.println(emp);
        }
    }

    @Test
    public void testDelete() throws Exception {
        empService.deleteById(51L);
    }

    @Test
    public void testUpdate() throws Exception {
        //update
        Emp emp = new Emp();
        emp.setHobby("zzzz");
        emp.setName("aaa");
        emp.setId(38L);
        empService.updateById(emp);
    }

    @Test
    public void testPage() throws Exception {
        Page<Emp> page = new Page<>();
        //设置当前页显示条数
        page.setSize(3);
        //设置当前页是第几页
        page.setCurrent(2);
        
        Page<Emp> empPage = empService.selectPage(page);
        System.out.println("???"+empPage.getTotal());//0
        System.out.println("----------");
        //拿到所有记录?? records
        List<Emp> records = empPage.getRecords();
        for (Emp record : records) {
            System.out.println(record);
        }
    }

    @Test
    public void testByDIY() throws Exception {
        System.out.println(empService.findOne(48L));
    }
}

一般主要使用MybatisPlus做代码生成器使用,功能强大,配置简单-TaTa!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值