MybatisPlus入門

1、認識java

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的加強工具,在 MyBatis 的基礎上只作加強不作改變,爲簡化開發、提升效率而生。mysql

支持多種數據庫:支持 MySQL、MariaDB、Oracle、DB二、H二、HSQL、SQLite、Postgre、SQLServer200五、SQLServer 等多種數據庫。web

內置通用 Mapper、通用 Service,僅僅經過少許配置便可實現單表大部分 CRUD 操做,更有強大的條件構造器,知足各種使用需求,spring

內置代碼生成器:採用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置,sql

內置分頁插件:基於 MyBatis 物理分頁,開發者無需關心具體操做,配置好插件以後,寫分頁等同於普通 List 查詢。數據庫

2、代碼生成器apache

2.1.1 構建maven項目 mybatis_plus緩存

2.1.2 引入pom.xml依賴(springboot)springboot

 1 <properties>
 2         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 3         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 4         <java.version>1.8</java.version>
 5         <springboot.version>2.0.5.RELEASE</springboot.version>
 6     </properties>
 7 
 8 
 9     <dependencyManagement>
10         <dependencies>
11             <dependency>
12                 <groupId>org.springframework.boot</groupId>
13                 <artifactId>spring-boot-dependencies</artifactId>
14                 <version>${springboot.version}</version>
15                 <type>pom</type>
16                 <scope>import</scope>
17             </dependency>
18         </dependencies>
19     </dependencyManagement>
20 
21     <build>
22         <plugins>
23             <plugin>
24                 <groupId>org.apache.maven.plugins</groupId>
25                 <artifactId>maven-compiler-plugin</artifactId>
26                 <version>3.5.1</version>
27                 <configuration>
28                     <source>1.8</source>
29                     <target>1.8</target>
30                 </configuration>
31             </plugin>
32         </plugins>
33     </build>

2.2.1 建立代碼生成器模板模塊  mp_generator  mybatis

2.2.2 導入pom.xml依賴

 1 <dependencies>
 2         <dependency>
 3             <groupId>org.springframework.boot</groupId>
 4             <artifactId>spring-boot-starter-web</artifactId>
 5         </dependency>
 6         <dependency>
 7             <groupId>org.springframework.boot</groupId>
 8             <artifactId>spring-boot-starter-test</artifactId>
 9         </dependency>
10 
11         <dependency>
12             <groupId>com.baomidou</groupId>
13             <artifactId>mybatis-plus-boot-starter</artifactId>
14             <version>2.2.0</version>
15         </dependency>
16 
17         <!--模板引擎-->
18         <dependency>
19             <groupId>org.apache.velocity</groupId>
20             <artifactId>velocity-engine-core</artifactId>
21             <version>2.0</version>
22         </dependency>
23         <!--數據庫驅動支持-->
24         <dependency>
25             <groupId>mysql</groupId>
26             <artifactId>mysql-connector-java</artifactId>
27         </dependency>
28 
29     </dependencies>

2.2.3 構建maven模塊  mp_project

2.2.4 導入依賴

 1 <dependencies>
 2         <dependency>
 3             <groupId>org.springframework.boot</groupId>
 4             <artifactId>spring-boot-starter-web</artifactId>
 5         </dependency>
 6         <dependency>
 7             <groupId>org.springframework.boot</groupId>
 8             <artifactId>spring-boot-starter-test</artifactId>
 9         </dependency>
10 
11         <dependency>
12             <groupId>com.baomidou</groupId>
13             <artifactId>mybatis-plus-boot-starter</artifactId>
14             <version>2.2.0</version>
15         </dependency>
16 
17         <dependency>
18             <groupId>mysql</groupId>
19             <artifactId>mysql-connector-java</artifactId>
20         </dependency>
21 
22     </dependencies>

 

2.2.5 代碼生成配置文件   mpconfig.properties

 1 #此處爲本項目src所在路徑(代碼生成器輸出路徑),注意必定是當前項目所在的目錄喲  2 OutputDir=E:/susu/ideawork/mybatis_plus/mp_project/src/main/java  3 #mapper.xml SQL映射文件目錄  4 OutputDirXml=E:/susu/ideawork/mybatis_plus/mp_project/src/main/resources  5 
 6 #咱們生產代碼要放的項目的地址:  7 OutputDirBase=E:/susu/ideawork/mybatis_plus/mp_project/src/main/java  8 #設置做者  9 author=bin 10 #自定義包路徑 11 parent=cn.su.yicheng.mp 12 
13 #數據庫鏈接信息 14 jdbc.driver=com.mysql.jdbc.Driver 15 jdbc.url=jdbc:mysql:///aigou_mp 16 jdbc.user=root 17 jdbc.pwd=000000

2.2.6 代碼生成方法  GenteratorCode.java

執行主方法,就能按照配置文件,根據數據庫表字段生成相應代碼

 1 package cu.su.yicheng.mp;  2 
 3 import com.baomidou.mybatisplus.generator.AutoGenerator;  4 import com.baomidou.mybatisplus.generator.InjectionConfig;  5 import com.baomidou.mybatisplus.generator.config.*;  6 import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;  7 import com.baomidou.mybatisplus.generator.config.po.TableInfo;  8 import com.baomidou.mybatisplus.generator.config.rules.DbType;  9 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;  10 
 11 import java.util.*;  12 
 13 public class GenteratorCode {  14 
 15     public static void main(String[] args) throws InterruptedException {  16         //用來獲取Mybatis-Plus.properties文件的配置信息
 17         ResourceBundle rb = ResourceBundle.getBundle("mpconfig");  18         AutoGenerator mpg = new AutoGenerator();  19         // 全局配置
 20         GlobalConfig gc = new GlobalConfig();  21         gc.setOutputDir(rb.getString("OutputDir"));  22         //覆蓋
 23         gc.setFileOverride(true);  24         gc.setActiveRecord(true);// 開啓 activeRecord 模式
 25         gc.setEnableCache(false);// XML 二級緩存
 26         gc.setBaseResultMap(true);// XML ResultMap
 27         gc.setBaseColumnList(false);// XML columList
 28         gc.setAuthor(rb.getString("author"));  29         gc.setOpen(false);//不打開文件夾
 30  mpg.setGlobalConfig(gc);  31         // 數據源配置
 32         DataSourceConfig dsc = new DataSourceConfig();  33         //設置你數據庫類型:
 34  dsc.setDbType(DbType.MYSQL);  35         dsc.setTypeConvert(new MySqlTypeConvert());  36         dsc.setDriverName(rb.getString("jdbc.driver"));  37         dsc.setUsername(rb.getString("jdbc.user"));  38         dsc.setPassword(rb.getString("jdbc.pwd"));  39         dsc.setUrl(rb.getString("jdbc.url"));  40  mpg.setDataSource(dsc);  41         // 策略配置
 42         StrategyConfig strategy = new StrategyConfig();  43         strategy.setTablePrefix(new String[] { "t_" });// 此處能夠修改成您的表前綴
 44         strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
 45         strategy.setInclude(new String[]{"t_emp"}); // 須要生成的表
 46  mpg.setStrategy(strategy);  47         // 包配置
 48         PackageConfig pc = new PackageConfig();  49         // parent:cn.itsource.aigou.mp
 50         pc.setParent(rb.getString("parent"));  51         pc.setController("controller");  52         pc.setService("service");  53         pc.setServiceImpl("service.impl");  54         pc.setEntity("domain");  55         pc.setMapper("mapper");  56  mpg.setPackageInfo(pc);  57 
 58         // 注入自定義配置,能夠在 VM 中使用 cfg.abc 【可無】
 59         InjectionConfig cfg = new InjectionConfig() {  60  @Override  61             public void initMap() {  62                 Map<String, Object> map = new HashMap<String, Object>();  63                 map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");  64                 this.setMap(map);  65  }  66  };  67 
 68         List<FileOutConfig> focList = new ArrayList<FileOutConfig>();  69 
 70         // 調整 domain 生成目錄演示
 71         focList.add(new FileOutConfig("/templates/entity.java.vm") {  72  @Override  73             public String outputFile(TableInfo tableInfo) {  74                 return rb.getString("OutputDirBase")+ "/cn/su/yicheng/mp/domain/" + tableInfo.getEntityName() + ".java";  75  }  76  });  77 
 78         // 調整 xml 生成目錄演示:原本mybatis的mapper.xml應該放到resources下:路徑應該和Mapper.java的路徑一致:
 79         focList.add(new FileOutConfig("/templates/mapper.xml.vm") {  80  @Override  81             public String outputFile(TableInfo tableInfo) {  82                 return rb.getString("OutputDirXml")+ "/cn/su/yicheng/mp/mapper/" + tableInfo.getEntityName() + "Mapper.xml";  83  }  84  });  85  cfg.setFileOutConfigList(focList);  86  mpg.setCfg(cfg);  87 
 88         // 自定義模板配置,能夠 copy 源碼 mybatis-plus/src/main/resources/templates 下面內容修改,  89         // 放置本身項目的 src/main/resources/templates 目錄下, 默認名稱一下能夠不配置,也能夠自定義模板名稱
 90         TemplateConfig tc = new TemplateConfig();  91         tc.setService("/templates/service.java.vm");  92         tc.setServiceImpl("/templates/serviceImpl.java.vm");  93         tc.setEntity(null);  94         tc.setMapper("/templates/mapper.java.vm");  95         tc.setController(null);  96         tc.setXml(null);  97         // 如上任何一個模塊若是設置 空 OR Null 將不生成該模塊。
 98  mpg.setTemplate(tc);  99 
100         // 執行生成
101  mpg.execute(); 102  } 103 
104 }

2.2.7 結果效果

2.3.1 測試

2.3.2 建立啓動類(MpApplication .java)和配置文件(application.yml)

 1 package cn.su.yicheng.mp;  2 
 3 import org.mybatis.spring.annotation.MapperScan;  4 import org.springframework.boot.SpringApplication;  5 import org.springframework.boot.autoconfigure.SpringBootApplication;  6 
 7 @SpringBootApplication  8 //掃描mapper文件
 9 @MapperScan(basePackages = "cn.su.yicheng.mp.mapper") 10 public class MpApplication { 11     public static void main(String[] args) { 12         SpringApplication.run(MpApplication.class); 13  } 14 }

 

 1 spring:  2  datasource:  3  driver-class-name: com.mysql.jdbc.Driver  4  url: jdbc:mysql://172.16.7.230:3306/wc  5 # url: jdbc:mysql:///yicheng_mp  6  username: root  7  password: admin  8 mybatis-plus:  9  # mapper.xml中給domain取別名 10   type-aliases-package: cn.su.yicheng.mp.domain

2.3.3 crud測試

 1 package cn.su.yicheng;  2 
 3 import cn.su.yicheng.mp.MpApplication;  4 import cn.su.yicheng.mp.domain.Emp;  5 import cn.su.yicheng.mp.service.IEmpService;  6 import com.baomidou.mybatisplus.mapper.EntityWrapper;  7 import com.baomidou.mybatisplus.mapper.Wrapper;  8 import com.baomidou.mybatisplus.plugins.Page;  9 import org.junit.Test; 10 import org.junit.runner.RunWith; 11 import org.springframework.beans.factory.annotation.Autowired; 12 import org.springframework.boot.test.context.SpringBootTest; 13 import org.springframework.test.context.junit4.SpringRunner; 14 
15 @RunWith(SpringRunner.class) 16 @SpringBootTest(classes = MpApplication.class) 17 public class MpTest { 18 
19  @Autowired 20     private IEmpService empService; 21 
22 
23     //添加測試
24  @Test 25     public void testAdd() throws Exception{ 26         Wrapper<Emp> wrapper = new EntityWrapper<>(); 27  empService.delete(wrapper); 28 
29         for (long i = 1; i <=10L ; i++) { 30             Emp emp = new Emp(); 31  emp.setId(i); 32             emp.setUsername("su"+i); 33             emp.setPassword("125"+i); 34  empService.insert(emp); 35  } 36  } 37 
38 
39     //查詢一條
40  @Test 41     public void testSelectOne() throws Exception{ 42         System.out.println(empService.selectById(2L)); 43  } 44 
45     //查詢所有
46  @Test 47     public void testSelectAll() throws Exception{ 48         Wrapper<Emp> wrapper = new EntityWrapper<>(); 49         empService.selectList(wrapper).forEach(e->{ 50  System.out.println(e); 51  }); 52  } 53 
54     //條件查詢
55  @Test 56     public void testSelectWhere() throws Exception{ 57         Wrapper<Emp> wrapper = new EntityWrapper<>(); 58         wrapper.eq("username", "su1"); 59         empService.selectList(wrapper).forEach(e->{ 60  System.out.println(e); 61  }); 62  } 63 
64 }

3、分頁

3.1 建立配置文件  MybatisPlusConfig.java

 1 package cn.su.yicheng.mp.config;  2 
 3 import com.baomidou.mybatisplus.plugins.PaginationInterceptor;  4 import org.mybatis.spring.annotation.MapperScan;  5 import org.springframework.context.annotation.Bean;  6 import org.springframework.context.annotation.Configuration;  7 import org.springframework.transaction.annotation.EnableTransactionManagement;  8 
 9 //Spring boot方式
10 @EnableTransactionManagement 11 @Configuration 12 @MapperScan("cn.su.yicheng.mp.mapper") 13 public class MybatisPlusConfig { 14 
15     /**
16  * 分頁插件 17      */
18  @Bean 19     public PaginationInterceptor paginationInterceptor() { 20         return new PaginationInterceptor(); 21  } 22 }

3.2 繼上面測試繼續

 1 //分頁查詢
 2  @Test  3     public void testPage() throws Exception{  4         Page page=new Page();  5         page.setSize(3);  6         page.setCurrent(1);  7         Page empPage = empService.selectPage(page);  8  System.out.println(page.getTotal());  9         empPage.getRecords().forEach(e->{ 10  System.out.println(e); 11  }); 12     }
相關文章
相關標籤/搜索