MybatisPlus---分页查询和代码生成器
第一步:创建好SpringBoot项目后先配置maven依赖(完整pom如下)
注意:1.启动类上要加注解@MapperScan("com.zk.*.mapper") // 扫码mapper类,把bean加入到spring容器管理
2..pom中resources配置不可缺少
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | <?xml version= "1.0" encoding= "UTF-8" ?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion> 4.0 . 0 </modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version> 2.5 . 4 </version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zk</groupId> <artifactId>mybatisplus</artifactId> <version> 0.0 . 1 -SNAPSHOT</version> <name>mybatisplus</name> <description>Demo project for Spring Boot</description> <properties> <java.version> 1.8 </java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </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 . 30 </version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- 打包时去除test测试类 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skip> true </skip> </configuration> </plugin> </plugins> <resources> <!--自动生成时候generate插件找到包,使用mybatis generator插件生成代码时先注掉--> <resource> <directory>lib</directory> <targetPath>BOOT-INF/lib/</targetPath> <includes> <include>** /*.jar</include> </includes> </resource> <!-- maven项目中src源代码下的xml等资源文件编译进classes文件夹,注意:如果没有这个,它会自动搜索resources下是否有mapper.xml文件, 如果没有就会报org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): 很重要 --> <resource> <directory>src/main/java</directory> <includes> <include>**/ *.xml</include> </includes> </resource> <!-- 把resources下的文件编译进classes文件夹 --> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering> false </filtering> </resource> </resources> </build> </project> |
第二步:在application.yml添加mybatis-plus配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #mybatis: # mapper-locations: classpath:com/mapper/xml /*.xml #注意:一定要对应mapper映射xml文件的所在路径 # type-aliases-package: com.model # 注意:对应实体类的路径 # configuration: #打印sql # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mybatis-plus: configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:com/zk/mybatisplus/**/ *Mapper.xml global-config: # 关闭MP3. 0 自带的banner banner: false # 逻辑删除配置 db-config: # 删除前 logic-not-delete-value: 1 # 删除后 logic-delete-value: 0 |
第三步:需要配置一下分页插件
1 2 3 4 5 6 7 8 9 10 | @Configuration public class MybatisPlusConfig { /** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } |
第四步:config目录下创建PageFactory类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class PageFactory { /** * 创建默认分页page */ public static Page page() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); //第几页 int pageNum = 1 ; //每页多少条数据 int limit = 10 ; if (StringUtils.isNotBlank(request.getParameter( "pageNum" ))) { pageNum = Integer.valueOf(request.getParameter( "pageNum" )); } if (StringUtils.isNotBlank(request.getParameter( "limit" ))) { limit = Integer.valueOf(request.getParameter( "limit" )); } return page(pageNum, limit); } /** * 创建默认分页page */ public static Page page(Integer pageNum, Integer limit) { return new Page(pageNum, limit); } /** * 创建默认分页page */ public static Page resultPage(List<Object> list) { Page page = page(); page.setRecords(list); page.setTotal(list.size()); int totalPagesNum = ( int ) (page.getTotal() / page.getSize()); page.setPages((page.getTotal() % page.getSize() == 0 ) ? totalPagesNum : totalPagesNum + 1 ); return page; } } |
第五步:配置mybatis-plus的代码生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | /** * 代码生成器 */ public class GeneratorCodeConfig { 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( "zk" ); gc.setOpen( false ); //实体属性 Swagger2 注解 gc.setSwagger2( false ); gc.setFileOverride( true ); //是否覆盖 gc.setActiveRecord( true ); gc.setEnableCache( false ); // XML 二级缓存 gc.setBaseResultMap( true ); // XML中的ResultMap标签 gc.setBaseColumnList( false ); // XML标签 gc.setIdType(IdType.AUTO); //主键策略 gc.setDateType(DateType.ONLY_DATE); // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setControllerName( "%sController" ); gc.setServiceName( "%sService" ); gc.setServiceImplName( "%sServiceImpl" ); gc.setMapperName( "%sMapper" ); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl( "jdbc:mysql://localhost:3306/user" ); 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" ); pc.setController( "zk.mybatisplus.controller" ); pc.setEntity( "zk.mybatisplus.model" ); pc.setMapper( "zk.mybatisplus.mapper" ); pc.setService( "zk.mybatisplus.service" ); pc.setServiceImpl( "zk.mybatisplus.service.impl" ); pc.setXml( "zk.mybatisplus.mapper.xml" ); 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/java/com/zk/mybatisplus/mapper/xml" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); System.out.println( pc.getModuleName()); /* 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); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass( "com.baomidou.mybatisplus.extension.activerecord.Model" ); strategy.setEntityLombokModel( true ); strategy.setRestControllerStyle( true ); strategy.setEntityLombokModel( true ); // 公共父类 // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 写于父类中的公共字段 // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner( "表名,多个英文逗号分割" ).split( "," )); strategy.setControllerMappingHyphenStyle( true ); strategy.setTablePrefix(pc.getModuleName() + "_" ); mpg.setStrategy(strategy); mpg.setTemplateEngine( new FreemarkerTemplateEngine()); mpg.execute(); } } |
运行之后,输入表名,生成表对应的model,service等文件。
如果运行代码生成器报错Exception in thread “main” java.lang.NoClassDefFoundError: freemarker/template/Configuration
问题可能原因:使用spring-boot-starter-test依赖
解决方案:1.注释掉spring-boot-starter-test依赖
2.复制此配置类到test目录运行
第六步:代码案例测试
controller层
注意:传入参数为pageNo和pageSize 所以在serviceImpl实现类里用的是PageFactory中第二个page方法,如果想用第一个page方法,传入参数名需和第一个page方法保持一致,并且参数不用写入方法中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @RestController @RequestMapping ( "/role" ) @Api (value = "角色管理" , tags = "角色管理" ) public class TTenantRoleController { @Resource private TTenantRoleService service; @RequestMapping (value = "/findRoleByPage" , method = RequestMethod.POST) @ApiOperation (value = "分页获取所有角色" ) public IPage<TTenantRole> findRoleByPage( @ApiParam (name = "pageNo" , value = "当前页" ) @RequestParam (value = "pageNo" , required = false , defaultValue = "1" ) Integer pageNo, @ApiParam (name = "pageSize" , value = "每一页数据个数" ) @RequestParam (value = "pageSize" , required = false , defaultValue = "5" ) Integer pageSize) { return service.findRoleByPage(pageNo,pageSize); } } |
service层
1 2 3 | public interface TTenantRoleService extends IService<TTenantRole> { IPage<TTenantRole> findRoleByPage(Integer pageNo,Integer pageSize); } |
service实现层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Service public class TTenantRoleServiceImpl extends ServiceImpl<TTenantRoleMapper, TTenantRole> implements TTenantRoleService { @Resource private TTenantRoleMapper mapper; @Override public IPage<TTenantRole> findRoleByPage(Integer pageNo,Integer pageSize) { LambdaQueryWrapper<TTenantRole> query = Wrappers.lambdaQuery(); query.eq(TTenantRole::getValid, "Y" ); Page<TTenantRole> page = PageFactory.page(pageNo,pageSize); IPage<TTenantRole> tTenantRoleIPage = mapper.selectPage(page, query); return tTenantRoleIPage; } } |
mapper层
1 2 | public interface TTenantRoleMapper extends BaseMapper<TTenantRole> { } |
启动项目,访问效果如下图:
查询第一页数据,每页两条数据,总数据条数为3,到此分页完成。
now ,fight for future
分类:
MyBatis
标签:
MyBatis-Plus
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程