经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
spring-cloud集成mybatis-plus
来源:cnblogs  作者:JCYL  时间:2019/3/8 9:09:47  对本文有异议

  mybatis-plus插件是对mybatis做出系列增强插件,后面简称MP,MP可免去开发者重复编写xml、mapper、service、entity等代码,通过MP提供的实体注解来完成单表的CRUD简单操作,MP同样配套有代码生成工具,可通过简单的配置来生成xml、mapper、service、entity等文件,极大提升了开发速度,本文是在spring-cloud的环境下集成mybatis-plus。

  spirng-cloud的基础环境搭建可参考https://www.cnblogs.com/xxpandong/p/10485172.html

  进入正文。

  ——————————————————————————————————————————————————————————————————————————————————————————————————————————————

  先来pom.xml文件

  

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>custom-authorize</groupId>
  6. <artifactId>custom-authorize</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <!-- 引入spring boot的依赖 -->
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.0.7.RELEASE</version>
  13. </parent>
  14. <properties>
  15. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  16. <java.version>1.8</java.version>
  17. </properties>
  18.  
  19. <dependencies>
  20. <!-- junit的spring-boot依赖 -->
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-test</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. <!-- alibaba fastjson 格式化对 -->
  27. <dependency>
  28. <groupId>com.alibaba</groupId>
  29. <artifactId>fastjson</artifactId>
  30. <version>1.1.41</version>
  31. </dependency>
  32. <!-- feign组件依赖 -->
  33. <dependency>
  34. <groupId>org.springframework.cloud</groupId>
  35. <artifactId>spring-cloud-starter-openfeign</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-web</artifactId>
  40. </dependency>
  41. <!-- jwt认证协议依赖 -->
  42. <dependency>
  43. <groupId>io.jsonwebtoken</groupId>
  44. <artifactId>jjwt</artifactId>
  45. <version>0.9.0</version>
  46. </dependency>
  47. <!-- redis依赖 -->
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-data-redis</artifactId>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.apache.commons</groupId>
  54. <artifactId>commons-pool2</artifactId>
  55. </dependency>
  56.  
  57. <!-- eureka服务组件 -->
  58. <dependency>
  59. <groupId>org.springframework.cloud</groupId>
  60. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  61. </dependency>
  62. <!-- MYSQL -->
  63. <dependency>
  64. <groupId>mysql</groupId>
  65. <artifactId>mysql-connector-java</artifactId>
  66. </dependency>
  67.  
  68. <!-- Mybatis依赖 -->
  69. <!-- <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId>
  70. <version>1.3.1</version> </dependency> -->
  71. <dependency>
  72. <groupId>com.baomidou</groupId>
  73. <artifactId>mybatis-plus-boot-starter</artifactId>
  74. <version>3.0-gamma</version>
  75. </dependency>
  76. <!-- 引入Lombok -->
  77. <dependency>
  78. <groupId>org.projectlombok</groupId>
  79. <artifactId>lombok</artifactId>
  80. <optional>true</optional>
  81. </dependency>
  82. <!-- mybatis-plus代码生成器模板引擎 -->
  83. <dependency>
  84. <groupId>org.freemarker</groupId>
  85. <artifactId>freemarker</artifactId>
  86. </dependency>
  87. </dependencies>
  88.  
  89. <!-- 引入spring cloud的依赖,不能少,主要用来管理Spring Cloud生态各组件的版本 -->
  90. <dependencyManagement>
  91. <dependencies>
  92. <dependency>
  93. <groupId>org.springframework.cloud</groupId>
  94. <artifactId>spring-cloud-dependencies</artifactId>
  95. <version>Finchley.SR2</version>
  96. <type>pom</type>
  97. <scope>import</scope>
  98. </dependency>
  99. </dependencies>
  100. </dependencyManagement>
  101.  
  102. <!-- 添加spring-boot的maven插件,不能少,打jar包时得用 -->
  103. <build>
  104. <plugins>
  105. <plugin>
  106. <groupId>org.springframework.boot</groupId>
  107. <artifactId>spring-boot-maven-plugin</artifactId>
  108. </plugin>
  109. </plugins>
  110. </build>
  111.  
  112.  
  113. </project>
View Code

 

  里面部分jar包是微服务所需jar包,核心jar包commons-pool2、mysql-connector-java、mybatis-plus-boot-starter、lombok、freemarker、spring-cloud、spring-boot这几个,其他的不需要可以删掉。

  lombok可以极大减少实体重复代码的编写,例如get/set/toString/constrator等,感兴趣的朋友可以去度娘一下,基本就是几个注解。

  这里使用的是3.x版本的MP插件,支持jdk1.8的特性,文档地址:https://baomidou.gitee.io/mybatis-plus-doc/#/quick-start

 

 

再来编写入口类:

  1. package com.authorize;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. import org.springframework.cloud.openfeign.EnableFeignClients;
  7. import org.springframework.context.annotation.Bean;
  8. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
  9. /**
  10. * 入口类
  11. * @title AuthorizeApplication.java
  12. * @package com.authorize
  13. * @description TODO(一句话描述该类作用)
  14. * @author Pandong
  15. * @date 2019年2月22日
  16. */
  17. @SpringBootApplication
  18. @EnableFeignClients // 服务之间通信所需注解
  19. @EnableEurekaClient     //  基于spring-boot环境的可以删掉上面及本行注解
  20. @MapperScan("com.authorize.dao")
  21. public class AuthorizeApplication {
  22. public static void main(String[] args) {
  23. SpringApplication.run(AuthorizeApplication.class, args);
  24. }
  25. /**
  26. * MP分页插件,后面会有说明
  27. */
  28. @Bean
  29. public PaginationInterceptor paginationInterceptor() {
  30. return new PaginationInterceptor();
  31. }
  32. }

 

 

编写application.yml文件:

  1. server:
  2. port: 8082
  3. spring:
  4. application:
  5. # 指定注册到eureka server上的服务名称
  6. name: custom-authorize
  7. #################################redis配置########################################
  8. redis:
  9. host: 127.0.0.1
  10. password: 123
  11. port: 6379
  12. timeout: 10000 # 连接超时时间(毫秒)
  13. database: 0 # Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
  14. lettuce:
  15. pool:
  16. max-active: 8 # 连接池最大连接数(使用负值表示没有限制)默认 8
  17. max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)默认 -1
  18. max-idle: 8 # 连接池中的最大空闲连接默认 8
  19. min-idle: 0 # 连接池中的最小空闲连接默认 0
  20. #################################redis配置########################################
  21. #####################################################################################################
  22. # mysql 属性配置
  23. datasource:
  24. driver-class-name: com.mysql.jdbc.Driver
  25. url: jdbc:mysql://127.0.0.1:3306/web_custom
  26. username: root
  27. password: pd123
  28. # jpa:
  29. # hibernate:
  30. # #ddl-auto: create #ddl-auto:设为create表示每次都重新建表
  31. # ddl-auto: update #ddl-auto:设为update表示每次都不会重新建表
  32. # show-sql: true
  33. #####################################################################################################
  34. #####################################################################################################
  35. # mybatis mapper xml 配置
  36. #mybatis:
  37. # mybatis.type-aliases-package:指定domain类的基包,即指定其在*Mapper.xml文件中可以使用简名来代替全类名(看后边的UserMapper.xml介绍)
  38. #type-aliases-package:
  39. #mapper-locations: classpath:mybatis/mapper/*.xml
  40. #config-location: classpath:mybatis/mybatis-config.xml
  41. # mybatis-plus 配置
  42. mybatis-plus:
  43. # 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
  44. # 如果是放在resource目录 classpath:/mapper/*Mapper.xml
  45. config-location: classpath:/mybatis/mybatis-config.xml
  46. mapper-locations: classpath:/mybatis/mapper/*.xml
  47. #实体扫描,多个package用逗号或者分号分隔
  48. typeAliasesPackage: com.authorize.entity
  49. global-config:
  50. #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
  51. id-type: 3
  52. # 热加载mapper文件
  53. refresh: true
  54. db-config:
  55. db-type: mysql
  56. #####################################################################################################
  57. eureka:
  58. client:
  59. service-url:
  60. # 指定eureka server通信地址,注意/eureka/小尾巴不能少
  61. defaultZone: http://admin:123@localhost:8080/eureka/
  62. instance:
  63. # 是否注册IP到eureka server,如不指定或设为false,那就会注册主机名到eureka server
  64. prefer-ip-address: true
  65. logging:
  66. level:
  67. root: INFO
  68. org.hibernate: INFO
  69. org.hibernate.type.descriptor.sql.BasicBinder: TRACE
  70. org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
  71. com.authorize: DEBUG
View Code

 

 

编写mybatis-config.xml文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4.  
  5. <settings>
  6. <setting name="callSettersOnNulls" value="true"/>
  7.  
  8. <setting name="cacheEnabled" value="true"/>
  9.  
  10. <setting name="lazyLoadingEnabled" value="true"/>
  11.  
  12. <setting name="aggressiveLazyLoading" value="true"/>
  13.  
  14. <setting name="multipleResultSetsEnabled" value="true"/>
  15.  
  16. <setting name="useColumnLabel" value="true"/>
  17.  
  18. <setting name="useGeneratedKeys" value="false"/>
  19.  
  20. <setting name="autoMappingBehavior" value="PARTIAL"/>
  21.  
  22. <setting name="defaultExecutorType" value="SIMPLE"/>
  23.  
  24. <setting name="mapUnderscoreToCamelCase" value="true"/>
  25.  
  26. <setting name="localCacheScope" value="SESSION"/>
  27.  
  28. <setting name="jdbcTypeForNull" value="NULL"/>
  29.  
  30. </settings>
  31.  
  32. <typeAliases>
  33. <typeAlias alias="Integer" type="java.lang.Integer" />
  34. <typeAlias alias="Long" type="java.lang.Long" />
  35. <typeAlias alias="HashMap" type="java.util.HashMap" />
  36. <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
  37. <typeAlias alias="ArrayList" type="java.util.ArrayList" />
  38. <typeAlias alias="LinkedList" type="java.util.LinkedList" />
  39. </typeAliases>
  40.  
  41. </configuration>
View Code

 

 

 

编写实体类:

  1. 1 package com.authorize.entity;
  2. 2
  3. 3 import java.math.BigDecimal;
  4. 4 import com.baomidou.mybatisplus.annotation.TableName;
  5. 5 import com.baomidou.mybatisplus.annotation.IdType;
  6. 6 import com.baomidou.mybatisplus.extension.activerecord.Model;
  7. 7 import com.baomidou.mybatisplus.annotation.TableId;
  8. 8 import com.baomidou.mybatisplus.annotation.TableField;
  9. 9 import java.io.Serializable;
  10. 10
  11. 11 import lombok.Data;
  12. 12 import lombok.EqualsAndHashCode;
  13. 13 import lombok.experimental.Accessors;
  14. 14
  15. 15 /**
  16. 16 * <p>
  17. 17 *
  18. 18 * </p>
  19. 19 *
  20. 20 * @author Pandong
  21. 21 * @since 2019-03-05
  22. 22 */
  23. 23 @Data
  24. 24 @EqualsAndHashCode(callSuper = false)
  25. 25 @Accessors(chain = true)
  26. 26 @TableName("ct_user")
  27. 27 public class CtUser extends Model<CtUser> {
  28. 28
  29. 29 private static final long serialVersionUID = 1L;
  30. 30
  31. 31 /**
  32. 32 * 主键
  33. 33 */
  34. 34 @TableId(value = "user_id", type = IdType.AUTO)
  35. 35 private Long userId;
  36. 36
  37. 37 /**
  38. 38 * 用户名称
  39. 39 */
  40. 40 @TableField("user_name")
  41. 41 private String userName;
  42. 42
  43. 43 /**
  44. 44 * 年龄
  45. 45 */
  46. 46 private Integer age;
  47. 47
  48. 48 /**
  49. 49 * 价格
  50. 50 */
  51. 51 private BigDecimal balance;
  52. 52
  53. 53
  54. 54 @Override
  55. 55 protected Serializable pkVal() {
  56. 56 return this.userId;
  57. 57 }
  58. 58
  59. 59 }
View Code

 

可以看到实体类上面使用了与hibernate相似的注解,属性上面使用了TableId注解,属性还有其他注解,可自行去查看文档。

实体上其他注解都是lombok的注解,是不是减少了很多代码。

 

 

编写mapper:

  1. package com.authorize.dao;
  2. import com.authorize.entity.CtUser;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. /**
  5. * <p>
  6. * Mapper 接口
  7. * </p>
  8. *
  9. * @author Pandong
  10. * @since 2019-03-05
  11. */
  12. public interface CtUserMapper extends BaseMapper<CtUser> {
  13. }
View Code

 

没看错,只需要继承BaseMapper就可实现CRUD,里面有大量的基础方法提供调用,能满足大部分的单表以及分页操作。

mapper上面未使用@Mapper注解,是因为在入口类中增加了注解@MapperScan注解。

 

 

编写Service:

  1. package com.authorize.service.authorize;
  2. import com.authorize.entity.CtUser;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * <p>
  6. * 服务类
  7. * </p>
  8. *
  9. * @author Pandong
  10. * @since 2019-03-05
  11. */
  12. public interface ICtUserService extends IService<CtUser> {
  13. }
View Code

 

 

编写Impl:

  1. package com.authorize.service.impl;
  2. import com.authorize.entity.CtUser;
  3. import com.authorize.dao.CtUserMapper;
  4. import com.authorize.service.authorize.ICtUserService;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * <p>
  9. * 服务实现类
  10. * </p>
  11. *
  12. * @author Pandong
  13. * @since 2019-03-05
  14. */
  15. @Service
  16. public class CtUserServiceImpl extends ServiceImpl<CtUserMapper, CtUser> implements ICtUserService {
  17. }
View Code

 

 

service同样继承MP提供的顶级基类,里面包含了大量的基础方法提供调用。

 

编写完成后整体的目录结构:

 

 generatorTemplate目录是代码生成的自定义模板目录,后面说代码生成会说到。

 

最后编写测试类:

  1. package com.authorize.controller;
  2. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  3. import org.junit.Before;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.http.MediaType;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. import org.springframework.test.web.servlet.MockMvc;
  11. import org.springframework.test.web.servlet.ResultActions;
  12. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  13. import com.authorize.AuthorizeApplication;
  14. import com.authorize.service.authorize.ICtMenuService;
  15. /**
  16. *
  17. * @filename CtSysyserControllerTest.java
  18. * @pakage com.authorize.controller
  19. * @descption TODO(用一句话表述类的作用)
  20. * @author Pandong
  21. * @date 2019年3月5日
  22. */
  23. @RunWith(SpringJUnit4ClassRunner.class)
  24. @SpringBootTest(classes = AuthorizeApplication.class)
  25. public class CtSysyserControllerTest {
  26. @Autowired
  27. private ICtUserService ss;
  28.   

      //  由于我数据库中已经有数据,所以插入数据的代码就不写了
  29. @Test
  30. public void test() {
  31. CtUser CtUser = ss.selectById(1);
  32. System.out.println(user);
  33. }
  34. }

 

 

到这里MP已经集成进来了,单表基本不用自己去写任何代码,当然,上面只是基本的配置,现在来说分页插件如何使用。

官方文档中有多个分页的实现,这里只讲官方推荐的方式,在上面的入口类中已经添加了分页插件的初始化(使用spring同志请自行去看文档)。

  1. @Bean
  2. public PaginationInterceptor paginationInterceptor() {
  3. return new PaginationInterceptor();
  4. }

 

编写测试类:

  1. package com.authorize.controller;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7. import com.authorize.AuthorizeApplication;
  8. import com.authorize.entity.CtUser;
  9. import com.authorize.service.authorize.ICtUserService;
  10. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  11. import com.baomidou.mybatisplus.core.metadata.IPage;
  12. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  13. /**
  14. *
  15. * @filename CtSysyserControllerTest.java
  16. * @pakage com.authorize.controller
  17. * @descption TODO(用一句话表述类的作用)
  18. * @author Pandong
  19. * @date 2019年3月5日
  20. */
  21. @RunWith(SpringJUnit4ClassRunner.class)
  22. @SpringBootTest(classes = AuthorizeApplication.class)
  23. public class CtUserControllerTest {
  24. @Autowired
  25. private ICtUserService ss;
  26. @Test
  27. public void test() {
  28. IPage<CtUser> page = new Page<>(1, 20);
  29. QueryWrapper<CtUser> wapper = new QueryWrapper<>();
  30. page = ss.selectPage(page, wapper);
  31. System.out.println(page.getRecords());
  32. }
  33. }
View Code

 

MP实现分页只需要new Page就完了,这样就完成一个简单的分页查询。

可能有的朋友看不明白QueryWrapper是什么,QueryWrapper是MP对查询的封装,这里做一些简单的说明,详细的去文档中查看,国人大牛开发的,注释都是中文的。

  1. @Test
  2. public void test1() {
  3. IPage<CtUser> page = new Page<>(1, 20);
  4. QueryWrapper<CtUser> wapper = new QueryWrapper<>();
  5. LambdaQueryWrapper<CtUser> lambda = wapper.lambda();
  6. lambda.and( obj -> obj.eq(CtUser::getUserName, "张三").eq(CtUser::getAge, "30"));
  7. page = ss.selectPage(page, lambda);
  8. System.out.println(page.getRecords());
  9. }
View Code

 

 上面代码是一个简单的查询分页操作,MP支持lambda表达式以及1.8的一些新特性,看不明白函数接口、方法引用的可参考http://www.runoob.com/java/java8-new-features.html

LambdaQueryWrapper中封装了很多方法来构造各种不同的查询条件,上面所用到的and方法,查询的sql语句:SELECT user_id AS userId,user_name AS userName,age,balance FROM ct_user WHERE ( user_name = ? AND age = ? ) ,

里面还封装了eq、or、like等等,详细的可以去看官方文档,上文中就给出地址。

到这里MP基本的CURD已经算是完成了,最后再来说一下代码生成:

  1. package com.authorize.utils.generator;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import com.baomidou.mybatisplus.annotation.DbType;
  7. import com.baomidou.mybatisplus.generator.AutoGenerator;
  8. import com.baomidou.mybatisplus.generator.InjectionConfig;
  9. import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
  10. import com.baomidou.mybatisplus.generator.config.FileOutConfig;
  11. import com.baomidou.mybatisplus.generator.config.GlobalConfig;
  12. import com.baomidou.mybatisplus.generator.config.PackageConfig;
  13. import com.baomidou.mybatisplus.generator.config.StrategyConfig;
  14. import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
  15. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  16. import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
  17. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  18. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  19. /**
  20. * 基于mybatis-plus的代码成功工具
  21. *
  22. * @filename EntityGenerator.java
  23. * @pakage com.authorize.utils.generator
  24. * @descption TODO(用一句话表述类的作用)
  25. * @author Pandong
  26. * @date 2019年3月1日
  27. */
  28. public class EntityGenerator {
  29. public static void main(String[] args) {
  30. generator();
  31. }
  32. public static void generator() {
  33. AutoGenerator mpg = new AutoGenerator();
  34. // 选择 freemarker 引擎,默认 Veloctiy
  35. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  36. // 全局配置
  37. GlobalConfig gc = new GlobalConfig();
  38. gc.setAuthor("Pandong");
  39. gc.setOutputDir("D:\\workspace\\springcloud_learning\\custom-authorize\\src\\main\\java");
  40. gc.setFileOverride(false);// 是否覆盖同名文件,默认是false
  41. gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
  42. gc.setEnableCache(false);// XML 二级缓存
  43. gc.setBaseResultMap(true);// XML ResultMap
  44. gc.setBaseColumnList(false);// XML columList
  45. /* 自定义文件命名,注意 %s 会自动填充表实体属性! */
  46. // gc.setMapperName("%sDao");
  47. // gc.setXmlName("%sDao");
  48. // gc.setServiceName("MP%sService");
  49. // gc.setServiceImplName("%sServiceDiy");
  50. // gc.setControllerName("%sAction");
  51. mpg.setGlobalConfig(gc);
  52. // 数据源配置
  53. DataSourceConfig dsc = new DataSourceConfig();
  54. dsc.setDbType(DbType.MYSQL);
  55. dsc.setTypeConvert(new MySqlTypeConvert() {
  56. // 自定义数据库表字段类型转换【可选】
  57. public DbColumnType processTypeConvert(String fieldType) {
  58. System.out.println("转换类型:" + fieldType);
  59. // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
  60. return super.processTypeConvert(gc, fieldType);
  61. }
  62. });
  63. dsc.setDriverName("com.mysql.jdbc.Driver");
  64. dsc.setUsername("root");
  65. dsc.setPassword("pd123");
  66. dsc.setUrl("jdbc:mysql://localhost:3306/web_custom?useUnicode=true&characterEncoding=utf8");
  67. mpg.setDataSource(dsc);
  68. // 策略配置
  69. StrategyConfig strategy = new StrategyConfig();
  70. // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
  71. // strategy.setTablePrefix(new String[] { "ct_" });// 此处可以修改为您的表前缀
  72. strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
  73. strategy.setInclude(new String[] { "ct_authorize","ct_btn","ct_menu","ct_role","ct_sysuser","ct_user"}); // 需要生成的表
  74. strategy.setEntityLombokModel(true); // 生成lombox模型实体
  75. strategy.entityTableFieldAnnotationEnable(true); //
  76. // strategy.setExclude(new String[]{"test"}); // 排除生成的表
  77. // 自定义实体父类
  78. // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
  79. // 自定义实体,公共字段
  80. // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
  81. // 自定义 mapper 父类
  82. // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
  83. // 自定义 service 父类
  84. // strategy.setSuperServiceClass("com.authorize.service.authorize.IDGeneratorService");
  85. // 自定义 service 实现类父类
  86. // strategy.setSuperServiceImplClass("com.authorize.service.impl.IDGeneratorServiceImpl");
  87. // 自定义 controller 父类
  88. strategy.setSuperControllerClass("com.authorize.controller.BaseController");
  89. // 【实体】是否生成字段常量(默认 false)
  90. // public static final String ID = "test_id";
  91. // strategy.setEntityColumnConstant(true);
  92. // 【实体】是否为构建者模型(默认 false)
  93. // public User setName(String name) {this.name = name; return this;}
  94. // strategy.setEntityBuilderModel(true);
  95. mpg.setStrategy(strategy);
  96. // 包配置
  97. PackageConfig pc = new PackageConfig();
  98. pc.setParent("com.authorize");
  99. pc.setService("service.authorize");
  100. pc.setServiceImpl("service.impl");
  101. pc.setXml(null);
  102. pc.setMapper("dao");
  103. // pc.setModuleName("test");
  104. mpg.setPackageInfo(pc);
  105. // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
  106. InjectionConfig cfg = new InjectionConfig() {
  107. @Override
  108. public void initMap() {
  109. }
  110. };
  111. //
  112. // // 自定义 xxList.jsp 生成
  113. List<FileOutConfig> focList = new ArrayList<>();
  114. // focList.add(new FileOutConfig("/template/list.jsp.vm") {
  115. // @Override
  116. // public String outputFile(TableInfo tableInfo) {
  117. // // 自定义输入文件名称
  118. // return "D://my_" + tableInfo.getEntityName() + ".jsp";
  119. // }
  120. // });
  121. // cfg.setFileOutConfigList(focList);
  122. // mpg.setCfg(cfg);
  123. //
  124. // // 调整 xml 生成目录演示
  125. focList.add(new FileOutConfig("/mybatis/generatorTemplate/mapper.xml.ftl") {
  126. @Override
  127. public String outputFile(TableInfo tableInfo) {
  128. return "src/main/resources/mybatis/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
  129. }
  130. });
  131. cfg.setFileOutConfigList(focList);
  132. mpg.setCfg(cfg);
  133. //
  134. // // 关闭默认 xml 生成,调整生成 至 根目录
  135. // TemplateConfig tc = new TemplateConfig();
  136. // tc.setXml(null);
  137. // mpg.setTemplate(tc);
  138. // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
  139. // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
  140. // TemplateConfig tc = new TemplateConfig();
  141. // tc.setController("...");
  142. // tc.setEntity("...");
  143. // tc.setMapper("...");
  144. // tc.setXml("...");
  145. // tc.setService("...");
  146. // tc.setServiceImpl("...");
  147. // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
  148. // mpg.setTemplate(tc);
  149. // 执行生成
  150. mpg.execute();
  151. // 打印注入设置【可无】
  152. // System.err.println(mpg.getCfg().getMap().get("abc"));
  153. }
  154. }
View Code

 

上面是官网给出的例子改的DEMO,上面我自己改了代码生成的位置,使用的模板也改过了,模板可以从源码的templates中拷贝。

这里配置生成文件的位置,可自行修改位置。

这段代码就是修改xml生成的位置,以及使用自己修改过的模板。

 

 

说到这里基本集成已经完成了,包含了生成的系列代码,更详细的就去看官方文档。。。

 

原文链接:http://www.cnblogs.com/xxpandong/p/10490400.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号