springboot+mybatis+mybatis-plus分頁查詢(簡單實現)

最近在研究mybatis,而後就去找簡化mybatis開發的工具,發現就有通用Mapper和mybatis-plus兩個比較好的但是使用,但是通過對比發現仍是mybatis-plus比較好,我的以爲,勿噴。。。

集成仍是很是簡單的,而後就在研究怎麼分頁,開始研究通用mapper時發現有個pagehelper的分頁工具能夠和它搭配。而後反過來看是否是也能夠和mybatis-plus搭配使用呢?發現mybatis-plus以前是能夠支持的,升級成3.X以後就再也不支持了。而後就研究mybatis-plus自帶的分頁工具吧!今天就簡單的寫個例子吧!java

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 這是mybatis-plus依賴 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- 這是mybatis-plus的代碼自動生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- 這是模板引擎依賴 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  • 配置好pom.xml文件以後,理所固然的就須要配置application.yml了。
#端口號
    server:
      port: 8888
    #數據庫的配置信息
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/blog #本身的數據庫名稱
        username: root
        password: 123456
    mybatis:
      #開啓駝峯命名法
      configuration:
        map-underscore-to-camel-case: true
    mybatis-plus:
      # xml地址
      mapper-locations: classpath:mapper/*Mapper.xml
      # 實體掃描,多個package用逗號或者分號分隔
      type-aliases-package: com.zhouzhaodong.pagination.entity   #本身的實體類地址
      configuration:
        # 這個配置會將執行的sql打印出來,在開發或測試的時候能夠用
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  • 接下來就須要配置mybatis-plus的代碼生成器了。
/**
     * <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();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 實體屬性 Swagger2 註解
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //這裏有個模塊名的配置,能夠註釋掉不用。
//        pc.setModuleName(scanner("模塊名"));
//        pc.setParent("com.zhouxiaoxi.www");
        pc.setParent(scanner("模塊地址"));
        mpg.setPackageInfo(pc);

        // 自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 若是模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 若是模板引擎是 velocity
//         String templatePath = "/templates/mapper.xml.vm";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 若是你 Entity 設置了先後綴、此處注意 xml 的名稱會跟着發生變化!!
                return projectPath + "/src/main/resources/mapper/"
//                        +  + pc.getModuleName() + 若是放開上面的模塊名,這裏就有一個模塊名了
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判斷自定義文件夾是否須要建立
                checkDir("調用默認方法建立的目錄");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定義輸出模板
        //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據使用的模板引擎自動識別
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //數據庫表映射到實體的明明策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //數據庫表字段映射到實體的命名策略, 未指定按照 naming 執行
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //自定義繼承的Entity類全稱,帶包名
//        strategy.setSuperEntityClass("***");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //自定義繼承的Controller類全稱,帶包名
//        strategy.setSuperControllerClass("***");
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        //自定義基礎的Entity類,公共字段(可添加更多)
//        strategy.setSuperEntityColumns("id");
        //駝峯轉連字符
        strategy.setControllerMappingHyphenStyle(true);
        //表前綴
//        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

運行以後就會出現全部須要的文件了。mysql

clipboard.png

  • 須要配置一下分頁插件,新建一個文件MybatisPlusConfig。
//Spring boot方式
    @EnableTransactionManagement
    @Configuration
    public class MybatisPlusConfig {
    
        /**
         * 分頁插件
         */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            return new PaginationInterceptor();
        }
    }
  • 這樣就只須要在controller裏面寫方法就能夠了。
@RestController
    @RequestMapping("/student")
    public class StudentController {
    
        @Autowired
        IStudentService studentService;
    
        @RequestMapping(value = "/findAll",method = RequestMethod.POST)
        public Object findAll(HttpServletRequest request){
            //獲取前臺發送過來的數據
            Integer pageNo = Integer.valueOf(request.getParameter("pageNo"));
            Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
            IPage<Student> page = new Page<>(pageNo, pageSize);
            QueryWrapper<Student> wrapper = new QueryWrapper<>();
            Student student = new Student();
            student.setId(1);
            wrapper.setEntity(student);
            return studentService.page(page,wrapper);
        }
    
    }
  • 實現的效果爲:

clipboard.png

具體代碼在github上面已經上傳了,能夠去下載使用哦!
https://github.com/zhouzhaodo...git

相關文章
相關標籤/搜索