MybatisPlus入门

MyBatisPlus简介

1.项目肯定要访问数据操作,并且每个domain都有crud,需多次写重复代码。我们使用MybatisPlus,就不用写重复代码,并且还有模板的功能,可以一键生成daomin,query,mapper接口,mapper.xml,service,controller
2.MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生
3.特性
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词
内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击

结构

在这里插入图片描述

代码生成器实现(在springboot中使用)

创建一个模块mp-genterator
1.导jar包
<dependencies>
        <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.配置mpconfig.properties
#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=E:\\Idea\\IdeaWork\\mpparent\\mp-project\\src\\main\\java
##mapper.xml SQL映射文件目录
OutputDirXml=E:\\Idea\\IdeaWork\\mpparent\\mp-project\\src\\main\\resources

OutputDirBase=E:\\Idea\\IdeaWork\\mpparent\\mp-project\\src\\main\\java
#E:\Idea\IdeaWork\mpparent\mp-project\src\main
#设置作者
author=admin
#自定义包路径
parent=com.lining.mybatisplus

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://172.16.7.245/aigou
jdbc.user=root
jdbc.pwd=123
3.编写代码生成类(运行此类就可以在配置的相应路径生成所需代码,没有包也会自动创建)
public class GenteratorCode {

    public static void main(String[] args) throws InterruptedException {
        //用来获取mpconfig.properties文件的配置信息
        final 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"));
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName("com.mysql.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_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>();

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

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

测试MybatisPlus

创建一个模块mp-project
1.导jar包
<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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

    </dependencies>
2.配置application.yml(连接数据库)
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.16.7.245/aigou
    username: root
    password: 123
mybatis-plus:
  type-aliases-package: com.lining.mybatisplus.domain
3.运行GenteratorCode .java

在这里插入图片描述在这里插入图片描述

4.使用MybatisPlus中的方法(部分)
 @RunWith(SpringRunner.class)
    @SpringBootTest(classes = MybatisApplication.class)
    public class UserServiceImplTest {
    
        @Autowired
        private IUserService userService;
    
        /**
         * 添加
         * @throws Exception
         */
        @Test
        public void testAdd() throws Exception{
            User user = new User();
            user.setName("李四");
            user.setAge(2);
            user.setSex(true);
            userService.insert(user);
        }
/**
     * 查询
     * @throws Exception
     */
    @Test
    public void testFind() throws Exception{
        User user = userService.selectById(2l);
        System.out.println(user);

    }
    /**
     * 修改
     */
    @Test
    public void testUpdate() throws Exception{
        User user = userService.selectById(2l);
        user.setName("李宁");
        userService.updateById(user);
    }
    /**
     * 删除
     */
    @Test
    public void testDelete() throws Exception{
        userService.deleteById(1l);
    }

    /**
     * 查询所有
     * @throws Exception
     */
    @Test
    public void testQuery() throws Exception{

        List<User> users = userService.selectList(null);
        System.out.println(users);

    }
}
5.分页插件配置

1.创建一个bean类

 //Spring boot方式
    @EnableTransactionManagement
    @Configuration
    @MapperScan("cn.itsource.mybatisplus.mybatisplustest.mapper")
    public class MybatisPlusConfig {
    
        /**
         * 分页插件
         */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            return new PaginationInterceptor();
        }
    }

2.分页测试

@Test
    public void testQueryAndPage() throws Exception{

        //1 当前页
        //10 每页显示多少条
        Page<User> page = new Page(1,1);

       // Wrapper wrapper = new EntityWrapper();
       // wrapper.like("name", "zs");
        userService.selectPage(page);

        System.out.println("总数:"+page.getTotal());
        System.out.println(page.getRecords());
    }
  • 7
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 如果你想要入门 MyBatis-Plus,可以按照以下步骤进行: 1. 首先,你需要在你的项目中引入 MyBatis-Plus 的依赖。可以在你的项目的 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> ``` 请确保将最新版本号替换为你想要使用的 MyBatis-Plus 版本号。 2. 然后,你需要配置 MyBatis-Plus。你可以在你的项目中创建一个 MyBatisPlusConfig 类,并在该类中注册一些必要的 Bean。例如,如果你想要使用乐观锁插件,你可以在 MyBatisPlusConfig 类中注册一个 OptimisticLockerInterceptor 的 Bean,如下所示: ```java @Configuration public class MyBatisPlusConfig { @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } } ``` 这样就完成了乐观锁插件的注册。 3. 最后,你需要在 MyBatis 的配置文件中配置 MyBatis-Plus 的一些属性。例如,如果你想要在控制台输出 MyBatis-Plus 的日志,你可以在配置文件中添加以下配置: ``` mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl ``` 这样就完成了 MyBatis-Plus 的入门配置。 总结起来,要入门 MyBatis-Plus,你需要引入依赖、配置 MyBatisPlusConfig 类和配置 MyBatis-Plus 的属性。这样就可以开始使用 MyBatis-Plus 来简化开发和提高效率了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [MybatisPlus入门教程](https://blog.csdn.net/qq_44732432/article/details/129221273)[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: 100%"] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值