【mybatis-plus3.06】(最新版)基于SSM实现分页插件配置与使用

up
吃吃吃

https://github.com/baomidou/mybatis-plus/blob/3.0/CHANGELOG.md(mybatis-plus 更新日志)
从日志中可以看出mybatis-plus 优化了众多方法,同时也新增了众多类和方法,使用起来更加便捷灵活。

mybaits-plus 是我们使用频率相对多的插件,以下就是mybatis-plus3.06 实现分页的具体步骤:

所需依赖

<!--mybatis plus-->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>`在这里插入代码片`
      <version>3.0.6</version>
    </dependency>

mybatis-plus代码生成器(参考官网:http://mp.baomidou.com/guide/generator.html)

public class MyGenerator {
    /**
     * <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 + "!");
    }

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

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("jobob");
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/runoob?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("guest123");
        mpg.setDataSource(dsc);

        // 包配置
        final PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("");
        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 + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setSuperControllerClass("");
        strategy.setInclude(scanner("表名"));
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

代码生成器自动生成如下目录:
项目目录
/Resource/spring-mybatis.xml 相关配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.service"/>

    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置DataSource数据源 -->
    <!-- 阿里 druid 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <!-- 数据库基本信息配置 -->
        <property name="url" value="${druid.url}"/>
        <property name="username" value="${druid.username}"/>
        <property name="password" value="${druid.password}"/>
        <property name="driverClassName" value="${druid.driverClassName}"/>
        <property name="filters" value="${druid.filters}"/>

        <!-- 最大并发连接数 -->
        <property name="maxActive" value="${druid.maxActive}"/>

        <!-- 初始化连接数量 -->
        <property name="initialSize" value="${druid.initialSize}"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${druid.maxWait}"/>

        <!-- 最小空闲连接数 -->
        <property name="minIdle" value="${druid.minIdle}"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}"/>
        <property name="validationQuery" value="${druid.validationQuery}"/>
        <property name="testWhileIdle" value="${druid.testWhileIdle}"/>
        <property name="testOnBorrow" value="${druid.testOnBorrow}"/>
        <property name="testOnReturn" value="${druid.testOnReturn}"/>
        <property name="maxOpenPreparedStatements" value="${druid.maxOpenPreparedStatements}"/>

        <!-- 打开 removeAbandoned 功能 -->
        <property name="removeAbandoned" value="${druid.removeAbandoned}"/>

        <!-- 1800 秒,也就是 30 分钟 -->
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}"/>

        <!-- 关闭 abanded 连接时输出错误日志 -->
        <property name="logAbandoned" value="${druid.logAbandoned}"/>
    </bean>

    <!-- 调整 SqlSessionFactory 为 MyBatis-Plus 的 SqlSessionFactory -->
    <!-- 定义MybatisPlus的全局策略配置-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>

        <!--<property name="configLocation" value="classpath:mybatis-config.xml"/>-->

        <property name="configuration">
            <bean class="com.baomidou.mybatisplus.core.MybatisConfiguration">
                <!--开启下划线驼峰映射-->
                <property name="mapUnderscoreToCamelCase" value="true"/>
            </bean>
        </property>
        <!-- 别名处理 -->
        <property name="typeAliasesPackage" value="com.entity"/>
        <!-- 注入全局MP策略配置 -->
        <property name="globalConfig">
            <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
                <property name="dbConfig">
                    <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
                        <!--主键规则-->
                        <property name="idType" value="AUTO"/>
                        <!--表前缀-->
                        <!--<property name="tablePrefix" value="tbl_"/>-->
                    </bean>
                </property>
            </bean>
        </property>
        <property name="plugins">
            <array>
                <!-- 分页插件配置 -->
                <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
                </bean>
            </array>
        </property>

    </bean>

    <!-- 配置 MapperScan -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mapper"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

mybatis-plus 3.06 使用的类已改变:如下(但都是基于Interceptor主类实现)

  <property name="plugins">
            <array>
                <!-- 分页插件配置 -->
                <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
                </bean>
            </array>
        </property>

下面是测试类:

 前方高能==============================测试分页==================================
    @ResponseBody
    @RequestMapping("findAllSite")
    public IPage<WebSites> findAllSite(){
        Page<WebSites> p =new Page<WebSites>(1,2);//current:1 ,size:2
        IPage<WebSites> data= webSitesService.page(p);
        return  data;
    }

执行Sql 语句:
在这里插入图片描述
页面请求数据如下:
在这里插入图片描述

此外springboot 实现更佳便捷,官网有详细介绍

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值