SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實現數據庫訪問功能
1. 創建SpringBoot項目
1.1 引入依賴
pom.xml
<?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 http://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.3.3.RELEASE</version> </parent> <groupId>com.gcl</groupId> <artifactId>vue_day03_admin</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!--spring-web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <!--mybatis-plus代碼生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> </dependency> <!--mysql驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!--數據庫連接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--測試--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--lang3工具類--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> </dependency> </dependencies> <!-- maven插件,可以將應用打包成一個可執行的jar包;--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
1.2 編寫配置文件
application.yml
server: port: 8088 spring: datasource: driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: Root@123456 mybatis-plus: type-aliases-package: com.gcl.entity configuration: map-underscore-to-camel-case: true use-generated-keys: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath:com/gcl/mapper/*Mapper.xml logging: level: com.demo.mapper: debug
2. 編寫MybatisPlus代碼生成工具類
2.1 編寫代碼生成工具類
CodeGenerator.java
package com.gcl.utils; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.IColumnType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // 執行 main 方法控制臺輸入模塊表名回車自動生成對應項目目錄中 public class CodeGenerator { /** * <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 + "/vue_day03_admin/src/main/java"); gc.setAuthor("gcl"); // 是否打開輸出目錄,默認true gc.setOpen(false); // 開啟 ActiveRecord 模式,默認false gc.setActiveRecord(true); // 是否覆蓋已有文件 gc.setFileOverride(true); // XML 開啟 BaseResultMap gc.setBaseResultMap(true); // XML 開啟 baseColumnList gc.setBaseColumnList(true); // 自定義文件命名,註意 %s 會自動填充表實體屬性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sMapper"); gc.setServiceName("%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // 數據源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setUrl("jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&useSSL=false&characterEncoding=utf8"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("Root@123456"); dsc.setTypeConvert(new MySqlTypeConvert(){ // 自定義數據庫表字段類型轉換【可選】 @Override public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { System.out.println("轉換類型:" + fieldType); // 註意!!processTypeConvert 存在默認類型轉換,如果不是你要的效果請自定義返回、非如下直接返回。 return super.processTypeConvert(globalConfig, fieldType); } }); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // com.demo.user pc.setParent("com"); // pc.setModuleName("user"); pc.setModuleName(scanner("模塊名")); mpg.setPackageInfo(pc); // 自定義配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // TODO } }; mpg.setCfg(cfg); // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 自定義輸出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定義配置會被優先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸出文件名 , 如果你 Entity 設置瞭前後綴、此處註意 xml 的名稱會跟著發生變化!! return projectPath + "/vue_day03_admin/src/main/resources/com/gcl/mapper" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 此處可以修改為您的表前綴 strategy.setTablePrefix(new String[] { "tb_", "tsys_","t_" }); // 表名生成策略 strategy.setNaming(NamingStrategy.underline_to_camel); // 需要生成的表 strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); // strategy.setInclude(new String[] { "tb_user" }); strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
2.2 創建數據庫及表
創表語句
CREATE TABLE `t_user` ( `id` int(60) NOT NULL AUTO_INCREMENT COMMENT '主鍵', `username` varchar(255) DEFAULT NULL COMMENT '姓名', `salary` double(7,2) DEFAULT NULL COMMENT '薪水', `age` int(11) DEFAULT NULL, `desc` varchar(255) DEFAULT NULL COMMENT '描述', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2.3 測試代碼生成器
執行CodeGenerator類中的main方法
執行代碼生成器之後的結果
3. 添加分頁配置
MyBatisPlusConfig.java
package com.gcl.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @ClassName MyBatisPlusConfig * @Description TODO * @Author gcl * @Date 2021-03-18 8:36 **/ @Configuration public class MyBatisPlusConfig { /** * mybatis-plus 分頁插件 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; } }
4. 測試訪問接口從數據庫中獲取數據(帶分頁)
4.1 數據庫中添加5條數據
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('1', '張三', '2000.00', '23', '95年05月生'); INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('2', '李四', '3000.00', '24', '96年06年生'); INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('3', '王五', '4000.00', '25', '07年07年生'); INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('4', '趙六', '5000.00', '26', '08年08月生'); INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('5', '田七', '6000.00', '27', '09年09月生');
4.2 編寫查詢方法
package com.gcl.controller; import com.baomidou.mybatisplus.core.conditions.query.Query; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.gcl.entity.User; import com.gcl.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author gcl * @since 2021-04-10 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * * @param pageNo 當前頁 * @param pageSize 每頁顯示的記錄數 * @return */ @GetMapping public List<User> findList(int pageNo,int pageSize){ //創建查詢條件封裝器 QueryWrapper<User> wrapper = new QueryWrapper<>(); Page<User> page = new Page<>(pageNo, pageSize); IPage<User> iPage = userService.page(page, wrapper); List<User> records = iPage.getRecords(); return records; } }
4.3 用postman工具測試分頁
先測試第一頁每頁顯示3條記錄
查看第二頁的數據
到此這篇關於SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實現數據庫訪問功能的文章就介紹到這瞭,更多相關SpringBoot實現數據庫訪問內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- None Found