Spring boot对于我来说是一个刚接触的新东西,学习过程中,发现这东西还是很容易上手的,Spring boot没配置时会默认使用Spring data jpa,这东西可以说一个极简洁的工具,可是我还是比较喜欢用mybatis,工具是没有最好的,只有这合适自己的。

说到mybatis,最近有一个很好用的工具--------mybatis-Plus(官网),现在更新的版本是2.1.2,这里使用的也是这个版本。我比较喜欢的功能是代码生成器,条件构造器,这样就可以更容易的去开发了。

mybatisPlus官网上是有Spring boot整个的例子的,我也跟着它走了一篇,结果,程序没跑起来,后来才知道demo用的H2 database,和mysql根本不是同一样东西,所以各位想要整合mybatisPlus,可以不看官网的,可以少走弯路。

下面就是整合的过程

1、首先要把需要的jar文件都弄过来,pom.xml需要的东西如下

pom.xml(不完整)

  1. <!-- mybatis-plus begin -->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatisplus-spring-boot-starter</artifactId>
  5. <version>1.0.4</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.baomidou</groupId>
  9. <artifactId>mybatis-plus</artifactId>
  10. <version>2.1.2</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-jdbc</artifactId>
  15. </dependency>
  16. <!-- mybatis-plus end -->
  17. <!-- druid阿里巴巴数据库连接池 -->
  18. <dependency>
  19. <groupId>com.alibaba</groupId>
  20. <artifactId>druid</artifactId>
  21. <version>1.1.3</version>
  22. </dependency>
  1. <!--mysql-->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    </dependency>
  1. <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
    </dependency>

2、添加mybatis相关的配置,如账号、密码等。这里我使用了application.yml来配。

application.yml

  1. server:
  2. port: 8080
  3.  
  4. #spring
  5. spring:
  6. devtools:
  7. restart:
  8. enabled: true #这里是为了热部署的,与mybatis是无关的
  9.  
  10. #DATABASE CONFIG
  11. datasource:
  12. driver-class-name: com.mysql.jdbc.Driver
  13. username: root
  14. password: root
  15. url: jdbc:mysql://mysqldb:3306/tdx_shop?useUnicode=true&characterEncoding=utf-8
  16. type: com.alibaba.druid.pool.DruidDataSource #这里是配置druid连接池,以下都是druid的配置信息
  17. filters: stat,wall,log4j
  18. maxActive: 20
  19. initialSize: 1
  20. maxWait: 60000
  21. minIdle: 1
  22. timeBetweenEvictionRunsMillis: 60000
  23. minEvictableIdleTimeMillis: 300000
  24. validationQuery: select 'x'
  25. testWhileIdle: true
  26. testOnBorrow: false
  27. testOnReturn: false
  28. poolPreparedStatements: true
  29. maxOpenPreparedStatements: 20
  30. connection-properties: druid.stat.merggSql=ture;druid.stat.slowSqlMillis=5000
  31.  
  32. #mybatis
  33. mybatis:
  34. mapper-locations: classpath*:/mapper/**Mapper.xml #把xml文件放在com.XX.mapper.*中可能会出现找到的问题,这里把他放在resource下的mapper中
  35. #实体扫描,多个package用逗号或者分号分隔
  36. typeAliasesPackage: com.tdx.account_service.entity #这里是实体类的位置
  37. configuration:
  38. map-underscore-to-camel-case: true
  39. cache-enabled: false
  40. #logging
  41. logging:
  42. level: warn

配置的东西和我们以前用mybatis配置可以说差不多,但spring boot是没有xml配置文件的。注意一下红字的内容,基本没问题了。

3、mybatis-Plus配置文件------MybatisPlusConfig,首先上图说明一下文件路径。其中MybatisPlusConfig是放在config文件夹内,而xml文件是放在resouces下mapper中。

接着就是MybatisPlusConfig内容部分了

1
MybatisProperties.java
  1. package com.tdx.account_service.config;
  2.  
  3. import com.alibaba.druid.pool.DruidDataSource;
  4. import com.alibaba.druid.support.http.StatViewServlet;
  5. import com.alibaba.druid.support.http.WebStatFilter;
  6. import com.baomidou.mybatisplus.MybatisConfiguration;
  7. import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
  8. import com.baomidou.mybatisplus.entity.GlobalConfiguration;
  9. import com.baomidou.mybatisplus.enums.DBType;
  10. import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
  11. import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
  12. import com.baomidou.mybatisplus.plugins.parser.ISqlParser;
  13. import com.baomidou.mybatisplus.plugins.parser.ISqlParserFilter;
  14. import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
  15. import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
  16. import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
  17. import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS;
  18. import com.baomidou.mybatisplus.toolkit.PluginUtils;
  19. import net.sf.jsqlparser.expression.Expression;
  20. import net.sf.jsqlparser.expression.LongValue;
  21. import org.apache.ibatis.mapping.DatabaseIdProvider;
  22. import org.apache.ibatis.mapping.MappedStatement;
  23. import org.apache.ibatis.plugin.Interceptor;
  24. import org.apache.ibatis.reflection.MetaObject;
  25. import org.mybatis.spring.annotation.MapperScan;
  26. import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
  27. import org.springframework.beans.factory.annotation.Autowired;
  28. import org.springframework.boot.bind.RelaxedPropertyResolver;
  29. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  30. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  31. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  32. import org.springframework.context.annotation.Bean;
  33. import org.springframework.context.annotation.Configuration;
  34. import org.springframework.core.env.Environment;
  35. import org.springframework.core.io.DefaultResourceLoader;
  36. import org.springframework.core.io.ResourceLoader;
  37. import org.springframework.util.ObjectUtils;
  38. import org.springframework.util.StringUtils;
  39.  
  40. import javax.sql.DataSource;
  41. import java.sql.SQLException;
  42. import java.util.ArrayList;
  43. import java.util.List;
  44.  
  45. /**
  46. * code is far away from bug with the animal protecting
  47. * ┏┓   ┏┓
  48. * ┏┛┻━━━┛┻┓
  49. * ┃       ┃
  50. * ┃   ━   ┃
  51. * ┃ ┳┛ ┗┳ ┃
  52. * ┃       ┃
  53. * ┃   ┻   ┃
  54. * ┃       ┃
  55. * ┗━┓   ┏━┛
  56. *   ┃   ┃神兽保佑
  57. *   ┃   ┃代码无BUG!
  58. *   ┃   ┗━━━┓
  59. *   ┃       ┣┓
  60. *   ┃       ┏┛
  61. *   ┗┓┓┏━┳┓┏┛
  62. *    ┃┫┫ ┃┫┫
  63. *    ┗┻┛ ┗┻┛
  64. *
  65. *
  66. * @Description : MybatisPlus配置
  67. * ---------------------------------
  68. * @Author : Liang.Guangqing
  69. * @Date : Create in 2017/9/19 13:54
  70. */
  71. @Configuration
  72. @EnableConfigurationProperties(MybatisProperties.class)
  73. public class MybatisPlusConfig {
  74.  
  75. @Autowired
  76. private Environment environment;
  77. private RelaxedPropertyResolver propertyResolver;
  78. @Autowired
  79. private DataSource dataSource;
  80. @Autowired
  81. private MybatisProperties properties;
  82. @Autowired
  83. private ResourceLoader resourceLoader = new DefaultResourceLoader();
  84. @Autowired(required = false)
  85. private Interceptor[] interceptors;
  86. @Autowired(required = false)
  87. private DatabaseIdProvider databaseIdProvider;
  88.  
  89. /**
  90. * @Description : mybatis-plus SQL执行效率插件【生产环境可以关闭】
  91. * ---------------------------------
  92. * @Author : Liang.Guangqing
  93. * @Date : Create in 2017/9/19 13:57
  94. */
  95. @Bean
  96. public PerformanceInterceptor performanceInterceptor() {
  97. return new PerformanceInterceptor();
  98. }
  99.  
  100. /**
  101. * 配置DataSource
  102. * @return
  103. * @throws SQLException
  104. */
  105. @Bean
  106. public DataSource druidDataSource() throws SQLException {
  107. this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
  108.  
  109. System.out.println("====================注入druid!====================");
  110. DruidDataSource datasource = new DruidDataSource();
  111. datasource.setUrl(propertyResolver.getProperty("url"));
  112. datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
  113. datasource.setUsername(propertyResolver.getProperty("username"));
  114. datasource.setPassword(propertyResolver.getProperty("password"));
  115. datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
  116. datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
  117. datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
  118. datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
  119. datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
  120. try {
  121. datasource.setFilters(propertyResolver.getProperty("filters"));
  122. } catch (SQLException e) {
  123. e.printStackTrace();
  124. }
  125. return datasource;
  126. }
  127.  
  128. /**
  129. * @Description : mybatis-plus分页插件
  130. * ---------------------------------
  131. * @Author : Liang.Guangqing
  132. * @Date : Create in 2017/9/19 13:59
  133. */
  134. @Bean
  135. public PaginationInterceptor paginationInterceptor() {
  136. PaginationInterceptor page = new PaginationInterceptor();
  137. page.setDialectType("mysql");
  138. return page;
  139. }
  140.  
  141. /**
  142. * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定
  143. * 配置文件和mybatis-boot的配置文件同步
  144. * @return
  145. */
  146. @Bean
  147. public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
  148. MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
  149. mybatisPlus.setDataSource(dataSource);
  150. mybatisPlus.setVfs(SpringBootVFS.class);
  151. if (StringUtils.hasText(this.properties.getConfigLocation())) {
  152. mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
  153. }
  154. mybatisPlus.setConfiguration(properties.getConfiguration());
  155. if (!ObjectUtils.isEmpty(this.interceptors)) {
  156. mybatisPlus.setPlugins(this.interceptors);
  157. }
  158. // MP 全局配置,更多内容进入类看注释
  159. GlobalConfiguration globalConfig = new GlobalConfiguration();
  160. globalConfig.setDbType(DBType.MYSQL.name());
  161. // ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
  162. globalConfig.setIdType(2);
  163. mybatisPlus.setGlobalConfig(globalConfig);
  164. MybatisConfiguration mc = new MybatisConfiguration();
  165. mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
  166. mybatisPlus.setConfiguration(mc);
  167. if (this.databaseIdProvider != null) {
  168. mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
  169. }
  170. if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
  171. mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
  172. }
  173. if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
  174. mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
  175. }
  176. if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
  177. mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
  178. }
  179. return mybatisPlus;
  180. }
  181.  
  182. /**
  183. * 注册一个StatViewServlet
  184. * @return
  185. */
  186. @Bean
  187. public ServletRegistrationBean DruidStatViewServle(){
  188. //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
  189. ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
  190. //添加初始化参数:initParams
  191. //白名单:
  192. // servletRegistrationBean.addInitParameter("allow","127.0.0.1");
  193. //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
  194. // servletRegistrationBean.addInitParameter("deny","192.168.1.73");
  195. //登录查看信息的账号密码.
  196. servletRegistrationBean.addInitParameter("loginUsername","root");
  197. servletRegistrationBean.addInitParameter("loginPassword","root");
  198. //是否能够重置数据.
  199. servletRegistrationBean.addInitParameter("resetEnable","false");
  200. return servletRegistrationBean;
  201. }
  202.  
  203. /**
  204. * 注册一个:filterRegistrationBean
  205. *
  206. * @return
  207. */
  208. @Bean
  209. public FilterRegistrationBean druidStatFilter(){
  210. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
  211. //添加过滤规则.
  212. filterRegistrationBean.addUrlPatterns("/*");
  213. //添加不需要忽略的格式信息.
  214. filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
  215. return filterRegistrationBean;
  216. }
  217.  
  218. }

这里是完整的配置文件,需要注意的是引入的包,别引错了!

4、还要开启dao的扫描,很简单,就是在启动文件中添加@MapperScan("com.tdx.account_service.dao*"),如下是完整的

到这里,配置算是完成了,运行一下项目是可以运行起来的。

我觉得Mybatis-Plus最好玩得应该是代码生成器这部分内容,下面是代码生成器的使用过程

pom.xml上要加点东西

  1. <dependency>
  2. <groupId>org.apache.velocity</groupId>
  3. <artifactId>velocity-engine-core</artifactId>
  4. <version>2.0</version>
  5. </dependency>

1、代码生成器的配置文件

  1. MybatisPlusConfig.java
  1. /**
  2. * Copyright (c) 2011-2016, hubin (jobob@qq.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. * <p>
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.tdx.account_service.generator;
  17.  
  18. import java.io.File;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24.  
  25. import com.baomidou.mybatisplus.enums.FieldFill;
  26. import com.baomidou.mybatisplus.generator.AutoGenerator;
  27. import com.baomidou.mybatisplus.generator.InjectionConfig;
  28. import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
  29. import com.baomidou.mybatisplus.generator.config.FileOutConfig;
  30. import com.baomidou.mybatisplus.generator.config.GlobalConfig;
  31. import com.baomidou.mybatisplus.generator.config.PackageConfig;
  32. import com.baomidou.mybatisplus.generator.config.StrategyConfig;
  33. import com.baomidou.mybatisplus.generator.config.TemplateConfig;
  34. import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
  35. import com.baomidou.mybatisplus.generator.config.po.TableFill;
  36. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  37. import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
  38. import com.baomidou.mybatisplus.generator.config.rules.DbType;
  39. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  40.  
  41. /**
  42. *code is far away from bug with the animal protecting
  43. * ┏┓   ┏┓
  44. *┏┛┻━━━┛┻┓
  45. *┃       ┃  
  46. *┃   ━   ┃
  47. *┃ ┳┛ ┗┳ ┃
  48. *┃       ┃
  49. *┃   ┻   ┃
  50. *┃       ┃
  51. *┗━┓   ┏━┛
  52. *  ┃   ┃神兽保佑
  53. *  ┃   ┃代码无BUG!
  54. *  ┃   ┗━━━┓
  55. *  ┃       ┣┓
  56. *  ┃       ┏┛
  57. *  ┗┓┓┏━┳┓┏┛
  58. *   ┃┫┫ ┃┫┫
  59. *   ┗┻┛ ┗┻┛
  60. *  
  61. * @Description : MybatisPlus代码生成器
  62. * ---------------------------------
  63. * @Author : Liang.Guangqing
  64. * @Date : Create in 2017/9/19 14:48 
  65. */
  66. public class MysqlGenerator {
  67.  
  68. private static String packageName="account_service"; //文件路径
  69. private static String authorName="Liang.Guangqing"; //作者
  70. private static String table="sc_user"; //table名字
  71. private static String prefix="sc_"; //table前缀
  72. private static File file = new File(packageName);
  73. private static String path = file.getAbsolutePath();
  74.  
  75. public static void main(String[] args) {
  76. // 自定义需要填充的字段
  77. List<TableFill> tableFillList = new ArrayList<>();
  78. tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
  79. // 代码生成器
  80. AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
  81. // 全局配置
  82. new GlobalConfig()
  83. .setOutputDir(path+"/src/main/java")//输出目录
  84. .setFileOverride(true)// 是否覆盖文件
  85. .setActiveRecord(true)// 开启 activeRecord 模式
  86. .setEnableCache(false)// XML 二级缓存
  87. .setBaseResultMap(true)// XML ResultMap
  88. .setBaseColumnList(true)// XML columList
  89. .setOpen(false)//生成后打开文件夹
  90. .setAuthor(authorName)
  91. // 自定义文件命名,注意 %s 会自动填充表实体属性!
  92. .setMapperName("%sMapper")
  93. .setXmlName("%sMapper")
  94. .setServiceName("%sService")
  95. .setServiceImplName("%sServiceImpl")
  96. .setControllerName("%sController")
  97. ).setDataSource(
  98. // 数据源配置
  99. new DataSourceConfig()
  100. .setDbType(DbType.MYSQL)// 数据库类型
  101. .setTypeConvert(new MySqlTypeConvert() {
  102. // 自定义数据库表字段类型转换【可选】
  103. @Override
  104. public DbColumnType processTypeConvert(String fieldType) {
  105. System.out.println("转换类型:" + fieldType);
  106. // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
  107. // return DbColumnType.BOOLEAN;
  108. // }
  109. return super.processTypeConvert(fieldType);
  110. }
  111. })
  112. .setDriverName("com.mysql.jdbc.Driver")
  113. .setUsername("root")
  114. .setPassword("root")
  115. .setUrl("jdbc:mysql://127.0.0.1:3306/tdx_shop?characterEncoding=utf8")
  116. ).setStrategy(
  117. // 策略配置
  118. new StrategyConfig()
  119. // .setCapitalMode(true)// 全局大写命名
  120. //.setDbColumnUnderline(true)//全局下划线命名
  121. .setTablePrefix(new String[]{prefix})// 此处可以修改为您的表前缀
  122. .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
  123. .setInclude(new String[] { table }) // 需要生成的表
  124. .setRestControllerStyle(true)
  125. //.setExclude(new String[]{"test"}) // 排除生成的表
  126. // 自定义实体父类
  127. // .setSuperEntityClass("com.baomidou.demo.TestEntity")
  128. // 自定义实体,公共字段
  129. //.setSuperEntityColumns(new String[]{"test_id"})
  130. .setTableFillList(tableFillList)
  131. // 自定义 mapper 父类
  132. // .setSuperMapperClass("com.baomidou.demo.TestMapper")
  133. // 自定义 service 父类
  134. // .setSuperServiceClass("com.baomidou.demo.TestService")
  135. // 自定义 service 实现类父类
  136. // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
  137. // 自定义 controller 父类
  138. .setSuperControllerClass("com.tdx."+packageName+".controller.AbstractController")
  139. // 【实体】是否生成字段常量(默认 false)
  140. // public static final String ID = "test_id";
  141. // .setEntityColumnConstant(true)
  142. // 【实体】是否为构建者模型(默认 false)
  143. // public User setName(String name) {this.name = name; return this;}
  144. // .setEntityBuilderModel(true)
  145. // 【实体】是否为lombok模型(默认 false)<a href="https://projectlombok.org/">document</a>
  146. // .setEntityLombokModel(true)
  147. // Boolean类型字段是否移除is前缀处理
  148. // .setEntityBooleanColumnRemoveIsPrefix(true)
  149. // .setRestControllerStyle(true)
  150. // .setControllerMappingHyphenStyle(true)
  151. ).setPackageInfo(
  152. // 包配置
  153. new PackageConfig()
  154. //.setModuleName("User")
  155. .setParent("com.tdx."+packageName)// 自定义包路径
  156. .setController("controller")// 这里是控制器包名,默认 web
  157. .setEntity("entity")
  158. .setMapper("dao")
  159. .setService("service")
  160. .setServiceImpl("service.impl")
  161. //.setXml("mapper")
  162. ).setCfg(
  163. // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
  164. new InjectionConfig() {
  165. @Override
  166. public void initMap() {
  167. Map<String, Object> map = new HashMap<>();
  168. map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
  169. this.setMap(map);
  170. }
  171. }.setFileOutConfigList(Collections.<FileOutConfig>singletonList(new FileOutConfig("/templates/mapper.xml.vm") {
  172. // 自定义输出文件目录
  173. @Override
  174. public String outputFile(TableInfo tableInfo) {
  175. return path+"/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
  176. }
  177. }))
  178. ).setTemplate(
  179. // 关闭默认 xml 生成,调整生成 至 根目录
  180. new TemplateConfig().setXml(null)
  181. // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
  182. // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
  183. // .setController("...");
  184. // .setEntity("...");
  185. // .setMapper("...");
  186. // .setXml("...");
  187. // .setService("...");
  188. // .setServiceImpl("...");
  189. );
  190.  
  191. // 执行生成
  192. mpg.execute();
  193.  
  194. // 打印注入设置,这里演示模板里面怎么获取注入内容【可无】
  195. System.err.println(mpg.getCfg().getMap().get("abc"));
  196. }
  197.  
  198. }

文件中修改的内容还是很多的,最主要的还是mysql的连接信息,没理由你账号,密码都错了还能连得上吧,其次设置一下你生成的模板文件路径,我这里生成的路径在上面图可以看得到,是在com.tdx.account_service下的,注意,xml文件要放在resources下,不然是识别的,说找不到这个方法

按照官网的代码模板生成的文件基本是白白的,主要是mybatis-Plus集成了公共方法,很多常用的工具都可以引用了。在这里我提供一下我修改后Controller.java.vm文件,主要还是按照我自己的习惯去弄的

controller.java.vm

  1. package ${package.Controller};
  2.  
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5.  
  6. #if(${restControllerStyle})
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. #else
  10. import org.springframework.stereotype.Controller;
  11. #end
  12. #if(${superControllerClassPackage})
  13. import ${superControllerClassPackage};
  14. #end
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import com.baomidou.mybatisplus.mapper.EntityWrapper;
  17. import com.baomidou.mybatisplus.plugins.Page;
  18. import ${package.Service}.${table.serviceName};
  19. import ${package.Entity}.common.DatatablesJSON;
  20. import ${package.Entity}.common.JSONResult;
  21. import ${package.Entity}.${entity};
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24.  
  25. /**
  26. *code is far away from bug with the animal protecting
  27. * ┏┓   ┏┓
  28. *┏┛┻━━━┛┻┓
  29. *┃       ┃  
  30. *┃   ━   ┃
  31. *┃ ┳┛ ┗┳ ┃
  32. *┃       ┃
  33. *┃   ┻   ┃
  34. *┃       ┃
  35. *┗━┓   ┏━┛
  36. *  ┃   ┃神兽保佑
  37. *  ┃   ┃代码无BUG!
  38. *  ┃   ┗━━━┓
  39. *  ┃       ┣┓
  40. *  ┃       ┏┛
  41. *  ┗┓┓┏━┳┓┏┛
  42. *   ┃┫┫ ┃┫┫
  43. *   ┗┻┛ ┗┻┛
  44. *  
  45. * @description : ${entity} 控制器
  46. * ---------------------------------
  47. * @author ${author}
  48. * @since ${date}
  49. */
  50. #if(${restControllerStyle})
  51. @RestController
  52. #else
  53. @Controller
  54. #end
  55. @RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
  56. #if(${superControllerClass})
  57. public class ${table.controllerName} extends ${superControllerClass} {
  58. #else
  59. public class ${table.controllerName} {
  60. #end
  61. private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);
  62.  
  63. @Autowired
  64. public ${table.serviceName} ${table.entityPath}Service;
  65.  
  66. /**
  67. * @description : 获取分页列表
  68. * ---------------------------------
  69. * @author : ${author}
  70. * @since : Create in ${date}
  71. */
  72. @RequestMapping(value = "/get${entity}List",method = RequestMethod.POST)
  73. public Object get${entity}List(${entity} param , @RequestParam(value = "draw",defaultValue = "0") Integer draw,
  74. @RequestParam(value = "length") Integer length,
  75. @RequestParam(value = "start") Integer start) {
  76. DatatablesJSON<${entity}> resJson=new DatatablesJSON<>();
  77. try {
  78. Integer pageNo=getPageNo(start,length);
  79. Page<${entity}> page=new Page<${entity}>(pageNo,length);
  80. ${table.entityPath}Service.selectPage(page,new EntityWrapper<${entity}>(param));
  81. resJson.setDraw(draw++);
  82. resJson.setRecordsTotal(page.getTotal());
  83. resJson.setRecordsFiltered(page.getTotal());
  84. resJson.setData(page.getRecords());
  85. resJson.setSuccess(true);
  86. }catch (Exception e){
  87. resJson.setSuccess(false);
  88. resJson.setError("异常信息:{"+e.getClass().getName()+"}");
  89. logger.info("异常信息:{}"+e.getMessage());
  90. }
  91. return resJson;
  92. }
  93.  
  94. /**
  95. * @description : 通过id获取${entity}
  96. * ---------------------------------
  97. * @author : ${author}
  98. * @since : Create in ${date}
  99. */
  100. @RequestMapping(value = "/get${entity}ById",method = RequestMethod.GET)
  101. public Object get${entity}ById(String id) {
  102. JSONResult<${entity}> resJson = new JSONResult<>();
  103. try {
  104. ${entity} param= ${table.entityPath}Service.selectById(id);
  105. resJson.setData(param);
  106. resJson.setSuccess(true);
  107. }catch (Exception e) {
  108. resJson.setSuccess(false);
  109. resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
  110. logger.info("异常信息:{}"+e.getMessage());
  111. }
  112. return resJson;
  113. }
  114.  
  115. /**
  116. * @description : 通过id删除${entity}
  117. * ---------------------------------
  118. * @author : ${author}
  119. * @since : Create in ${date}
  120. */
  121. @RequestMapping(value = "/delete${entity}ById",method = RequestMethod.GET)
  122. public Object delete${entity}ById(String id) {
  123. JSONResult<${entity}> resJson = new JSONResult<>();
  124. try{
  125. resJson.setSuccess(${table.entityPath}Service.deleteById(id));
  126. }catch (Exception e) {
  127. resJson.setSuccess(false);
  128. resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
  129. logger.info("异常信息:{}"+e.getMessage());
  130. }
  131. return resJson;
  132. }
  133.  
  134. /**
  135. * @description : 通过id更新${entity}
  136. * ---------------------------------
  137. * @author : ${author}
  138. * @since : Create in ${date}
  139. */
  140. @RequestMapping(value = "/update${entity}ById",method = RequestMethod.POST)
  141. public Object update${entity}ById(${entity} param) {
  142. JSONResult<${entity}> resJson = new JSONResult<>();
  143. try{
  144. resJson.setSuccess(${table.entityPath}Service.updateById(param));
  145. }catch (Exception e) {
  146. resJson.setSuccess(false);
  147. resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
  148. logger.info("异常信息:{}"+e.getMessage());
  149. }
  150. return resJson;
  151. }
  152.  
  153. /**
  154. * @description : 添加${entity}
  155. * ---------------------------------
  156. * @author : ${author}
  157. * @since : Create in ${date}
  158. */
  159. @RequestMapping(value = "/add${entity}",method = RequestMethod.POST)
  160. public Object add${entity}(${entity} param) {
  161. JSONResult<${entity}> resJson = new JSONResult<>();
  162. try{
  163. resJson.setSuccess(${table.entityPath}Service.insert(param));
  164. }catch (Exception e) {
  165. resJson.setSuccess(false);
  166. resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
  167. logger.info("异常信息:{}"+e.getMessage());
  168. }
  169. return resJson;
  170. }
  171. }

除了这个文件,其他代码模板我都是按照官网那样的,这里引用3个外部的文件,有AbstractController.java(控制器基类)、DatatablesJSON.java和JSONResult.java,然后这些文件又引用了其他文件,我懵逼了,怎么文件这么多啊,看来如果全部都贴上来得多占地方啊,所以我选择相信码云,如果需要请在码云上按照少的文件下载,码云地址。需要注意的是,我的模板是直接代替了mybatis-plus.jar中的templates目录。

最后就到了测试过程

下面的代码段都是放在Controller文件里面,然后启动程序,对应端口,请求方法。测试的话是需要按照自己的实体类操作的,所以仅供参考。

  1. /**
  2. * 分页 PAGE
  3. */
  4. @GetMapping("/test")
  5. public Page<User> test() {
  6. return userService.selectPage(new Page<User>(0, 12));
  7. }
  8.  
  9. /**
  10. * AR 部分测试
  11. */
  12. @GetMapping("/test1")
  13. public Page<User> test1() {
  14. User user = new User();
  15. System.err.println("删除所有:" + user.delete(null));
  16. //user.setId(2017091801L);
  17. user.setAccout("test"+num++);
  18. user.setType("test");
  19. user.setCreateTime(new Date());
  20. user.setPhone("13111110000");
  21. user.setPassword("123456");
  22. user.setNickname("guangqing"+2*num++);
  23. user.insert();
  24. System.err.println("查询插入结果:" + user.selectById().toString());
  25. //user.setNickname("mybatis-plus-ar");
  26. System.err.println("更新:" + user.updateById());
  27. return user.selectPage(new Page<User>(0, 12), null);
  28. }
  29.  
  30. /**
  31. * 增删改查 CRUD
  32. */
  33. @GetMapping("/test2")
  34. public User test2() {
  35. User user = new User();
  36. user.setId(123456L);
  37. user.setAccout("test");
  38. user.setType("test");
  39. user.setCreateTime(new Date());
  40. user.setPhone("13111110000");
  41. user.setPassword("123456");
  42. user.setNickname("guangqing");
  43. System.err.println("删除一条数据:" + userService.deleteById(1L));
  44. System.err.println("插入一条数据:" + userService.insert(user));
  45. User user2 = new User();
  46. user.setId(223456L);
  47. user.setAccout("test2");
  48. user.setType("test");
  49. user.setCreateTime(new Date());
  50. user.setPhone("13111110000");
  51. user.setPassword("123456");
  52. user.setNickname("guangqing");
  53. boolean result = userService.insert(user);
  54. // 自动回写的ID
  55. Long id = user.getId();
  56. System.err.println("插入一条数据:" + result + ", 插入信息:" + user.toString());
  57. System.err.println("查询:" + userService.selectById(id).toString());
  58. Page<User> userListPage = userService.selectPage(new Page<User>(1, 5), new EntityWrapper<>(new User()));
  59. System.err.println("total=" + userListPage.getTotal() + ", current list size=" + userListPage.getRecords().size());
  60. return userService.selectById(1L);
  61. }
  62.  
  63. @GetMapping("testSelect")
  64. public Object testSelect() {
  65. Integer start = 0;
  66. Integer length =10;
  67. User param = new User();
  68. //param.setNickname("guangqing2");
  69. Integer pageNo=getPageNo(start,length);
  70. Page<User> page =new Page<User>(pageNo,length);
  71. EntityWrapper<User> ew = new EntityWrapper<User>();
  72. ew.setEntity(param);
  73. ew.where("password={0}","123456")
  74. .like("nickname","guangqing")
  75. .ge("create_time","2017-09-21 15:50:00");
  76. userService.selectPage(page, ew);
  77. DatatablesJSON<User> resJson= new DatatablesJSON<>();
  78. //resJson.setDraw(draw++);
  79. resJson.setRecordsTotal(page.getTotal());
  80. resJson.setRecordsFiltered(page.getTotal());
  81. resJson.setData(page.getRecords());
  82. return resJson;
  83. }
  84.  
  85. @GetMapping("/selectsql")
  86. public Object getUserBySql() {
  87. JSONObject result = new JSONObject();
  88. result.put("records", userService.selectListBySQL());
  89. return result;
  90. }
  91.  
  92. /**
  93. * 7、分页 size 一页显示数量 current 当前页码
  94. * 方式一:http://localhost:8080/user/page?size=1&current=1<br>
  95. * 方式二:http://localhost:8080/user/pagehelper?size=1&current=1<br>
  96. */
  97.  
  98. // 参数模式分页
  99. @GetMapping("/page")
  100. public Object page(Page page) {
  101. return userService.selectPage(page);
  102. }
  103.  
  104. // ThreadLocal 模式分页
  105. @GetMapping("/pagehelper")
  106. public Object pagehelper(Page page) {
  107. PageHelper.setPagination(page);
  108. page.setRecords(userService.selectList(null));
  109. page.setTotal(PageHelper.freeTotal());//获取总数并释放资源 也可以 PageHelper.getTotal()
  110. return page;
  111. }
  112.  
  113. /**
  114. * 测试事物
  115. * http://localhost:8080/user/test_transactional<br>
  116. * 访问如下并未发现插入数据说明事物可靠!!<br>
  117. * http://localhost:8080/user/test<br>
  118. * <br>
  119. * 启动 Application 加上 @EnableTransactionManagement 注解其实可无默认貌似就开启了<br>
  120. * 需要事物的方法加上 @Transactional 必须的哦!!
  121. */
  122. @Transactional
  123. @GetMapping("/test_transactional")
  124. public void testTransactional() {
  125. //userService.insert(new User(1000L, "测试事物", 16, 3));
  126. System.out.println(" 这里手动抛出异常,自动回滚数据");
  127. throw new RuntimeException();
  128. }

这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。

最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!

引自https://www.cnblogs.com/lianggp/p/7573653.html

spring boot整合mybatis+mybatis-plus的更多相关文章

  1. Spring Boot整合tk.mybatis及pageHelper分页插件及mybatis逆向工程

    Spring Boot整合druid数据源 1)引入依赖 <dependency> <groupId>com.alibaba</groupId> <artif ...

  2. spring boot 2.x 系列 —— spring boot 整合 druid+mybatis

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.说明 1.1 项目结构 项目查询用的表对应的建表语句放置在resour ...

  3. spring boot整合 springmvc+mybatis

    需要以下依赖 <dependencies> <dependency> <groupId>org.springframework.boot</groupId&g ...

  4. Spring Boot 整合 Druid

    Spring Boot 整合 Druid 概述 Druid 是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池.插件框架和 SQL 解析器组成.该项目主要是为了扩展 JDBC 的一些限制,可以让程 ...

  5. Spring Boot整合Mybatis并完成CRUD操作

    MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作. 为什么要使用Mybatis?我们需要掌握Mybatis吗? 说的官 ...

  6. Spring boot整合Mybatis

    时隔两个月的再来写博客的感觉怎么样呢,只能用“棒”来形容了.闲话少说,直接入正题,之前的博客中有说过,将spring与mybatis整个后开发会更爽,基于现在springboot已经成为整个业界开发主 ...

  7. spring boot 整合 mybatis 以及原理

    同上一篇文章一样,spring boot 整合 mybatis过程中没有看见SqlSessionFactory,sqlsession(sqlsessionTemplate),就连在spring框架整合 ...

  8. Spring Boot 中使用 MyBatis 整合 Druid 多数据源

    2017 年 10 月 20 日   Spring Boot 中使用 MyBatis 整合 Druid 多数据源 本文将讲述 spring boot + mybatis + druid 多数据源配置方 ...

  9. Spring Boot 整合mybatis时遇到的mapper接口不能注入的问题

    现实情况是这样的,因为在练习spring boot整合mybatis,所以自己新建了个项目做测试,可是在idea里面mapper接口注入报错,后来百度查询了下,把idea的注入等级设置为了warnin ...

  10. Spring Boot整合Mybatis报错InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    Spring Boot整合Mybatis时一直报错 后来发现原来主配置类上的MapperScan导错了包 由于我使用了通用Mapper,所以应该导入通用mapper这个包

随机推荐

  1. usb3.0 monitor is already started

    用360 开机加速里找到这个程序,把它从开机启动中删除掉就好.

  2. Qt Quick自定义样式一套

    弄了几个月的Qt,基本上以写上位机程序和工厂用的一些工具为主.老大的要求是快速.稳定.不出问题,不过他嫌.net要安装.还有升级(刚开始的时候由于这个出了些小问题),MFC开发东西又实在费劲,就让我找 ...

  3. Codeforces.997C.Sky Full of Stars(容斥 计数)

    题目链接 那场完整的Div2(Div1 ABC)在这儿.. \(Description\) 给定\(n(n\leq 10^6)\),用三种颜色染有\(n\times n\)个格子的矩形,求至少有一行或 ...

  4. spring data jpa在使用PostgreSQL表名大小写的问题解决

    国内的文章看了一遍,其实没找到根本问题解决方法,下面将列举这一系列的问题解决方法: 1.在配置文件增加如下配置: spring.jpa.hibernate.naming.physical-strate ...

  5. 异步接收MSMQ消息

    在这部分,我们将使用ThreadPool 和MSMQ 进行消息收发.MSMQ 是一个分布式队列,通过MSMQ 一个应用程序可以异步地与另外一个应用程序通信. 在一个典型的场景中,我们要向维护一个队列的 ...

  6. Snmp学习总结(五)——WindowsServer2008安装和配置SNMP

    一.安装SNMP 在Windows Server 2008以及Windows Server 2008 R2中,SNMP是以一个服务器功能的形式存在的,SNMP的安装步骤如下所示: 1.打开[开始]→[ ...

  7. JSP页面中使用JSTL标签出现无法解析问题解决办法

    今天建立一个JavaWeb工程测试JNDI数据源连接,在jsp页面中引入了JSLT标签库,代码如下: <%@ page language="java" import=&quo ...

  8. redis实现异步任务队列

    redis实现异步任务队列 先说思路: 将任务对象序列为JSON字符串,然后推入REDIS缓存,这叫入队. 通过独立的工作线程从REDIS拉出一个任务,这叫出队,工作线程将JSON字符串还原为任务对象 ...

  9. iPhone上将短信内容发送到指定邮箱的方法

    iPhone上将短信内容发送到指定邮箱的方法 迄今为止,移动应用安全基本聚焦在以下几个方面,一是移动设备管理BYOD(bring your own device),二是移动恶意软件分析,三是移动设备用 ...

  10. 安装oracle 11g环境变量ORACLE_HOME的一个问题 转

    http://blog.itpub.net/26129555/viewspace-1243467/报错内容: OUI-10137:An Oracle Home with name ORACLE_HOM ...