spring boot整合mybatis+mybatis-plus


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(不完整)

復制代碼
<!-- mybatis-plus begin -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatisplus-spring-boot-starter</artifactId>
    <version>1.0.4</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>2.1.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis-plus end -->
<!-- druid阿里巴巴數據庫連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version> </dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<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

復制代碼
server:
    port: 8080

spring

spring:
devtools:
restart:
enabled: true #這里是為了熱部署的,與mybatis是無關的

DATABASE CONFIG

datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql:
//mysqldb:3306/tdx_shop?useUnicode=true&characterEncoding=utf-8
type: com.alibaba.druid.pool.DruidDataSource #這里是配置druid連接池,以下都是druid的配置信息
filters: stat,wall,log4j
maxActive:
20
initialSize:
1
maxWait:
60000
minIdle:
1
timeBetweenEvictionRunsMillis:
60000
minEvictableIdleTimeMillis:
300000
validationQuery: select
'x'
testWhileIdle:
true
testOnBorrow:
false
testOnReturn:
false
poolPreparedStatements:
true
maxOpenPreparedStatements:
20
connection
-properties: druid.stat.merggSql=ture;druid.stat.slowSqlMillis=5000

mybatis

mybatis:
mapper-locations: classpath:/mapper/**Mapper.xml #把xml文件放在com.XX.mapper.中可能會出現找到的問題,這里把他放在resource下的mapper中

實體掃描,多個package用逗號或者分號分隔

typeAliasesPackage: com.tdx.account_service.entity #這里是實體類的位置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false

logging

logging:
level: warn

復制代碼

 

配置的東西和我們以前用mybatis配置可以說差不多,但spring boot是沒有xml配置文件的。注意一下紅字的內容,基本沒問題了。

3、mybatis-Plus配置文件------MybatisPlusConfig,首先上圖說明一下文件路徑。其中MybatisPlusConfig是放在config文件夾內,而xml文件是放在resouces下mapper中。

接着就是MybatisPlusConfig內容部分了

?
1
MybatisProperties.java
復制代碼
package com.tdx.account_service.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.plugins.parser.ISqlParser;
import com.baomidou.mybatisplus.plugins.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS;
import com.baomidou.mybatisplus.toolkit.PluginUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**

  • code is far away from bug with the animal protecting

  • ┏┓   ┏┓

  • ┏┛┻━━━┛┻┓

  • ┃       ┃

  • ┃   ━   ┃

  • ┃ ┳┛ ┗┳ ┃

  • ┃       ┃

  • ┃   ┻   ┃

  • ┃       ┃

  • ┗━┓   ┏━┛

  •   ┃   ┃神獸保佑

  •   ┃   ┃代碼無BUG!

  •   ┃   ┗━━━┓

  •   ┃       ┣┓

  •   ┃       ┏┛

  •   ┗┓┓┏━┳┓┏┛

  •    ┃┫┫ ┃┫┫

  •    ┗┻┛ ┗┻┛

  • @Description : MybatisPlus配置


  • @Author : Liang.Guangqing

  • @Date : Create in 2017/9/19 13:54
    */
    @Configuration
    @EnableConfigurationProperties(MybatisProperties.
    class)
    public class MybatisPlusConfig {

    @Autowired
    private Environment environment;
    private RelaxedPropertyResolver propertyResolver;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MybatisProperties properties;
    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    @Autowired(required
    = false)
    private Interceptor[] interceptors;
    @Autowired(required
    = false)
    private DatabaseIdProvider databaseIdProvider;

    /**

    • @Description : mybatis-plus SQL執行效率插件【生產環境可以關閉】

    • @Author : Liang.Guangqing
    • @Date : Create in 2017/9/19 13:57
      */
      @Bean
      public PerformanceInterceptor performanceInterceptor() {
      return new PerformanceInterceptor();
      }

    /**

    • 配置DataSource

    • @return

    • @throws SQLException
      */
      @Bean
      public DataSource druidDataSource() throws SQLException {
      this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");

      System.out.println("注入druid!");
      DruidDataSource datasource
      = new DruidDataSource();
      datasource.setUrl(propertyResolver.getProperty(
      "url"));
      datasource.setDriverClassName(propertyResolver.getProperty(
      "driver-class-name"));
      datasource.setUsername(propertyResolver.getProperty(
      "username"));
      datasource.setPassword(propertyResolver.getProperty(
      "password"));
      datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty(
      "initial-size")));
      datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty(
      "min-idle")));
      datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty(
      "max-wait")));
      datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty(
      "max-active")));
      datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty(
      "min-evictable-idle-time-millis")));
      try {
      datasource.setFilters(propertyResolver.getProperty(
      "filters"));
      }
      catch (SQLException e) {
      e.printStackTrace();
      }
      return datasource;
      }

    /**

    • @Description : mybatis-plus分頁插件

    • @Author : Liang.Guangqing
    • @Date : Create in 2017/9/19 13:59
      */
      @Bean
      public PaginationInterceptor paginationInterceptor() {
      PaginationInterceptor page
      = new PaginationInterceptor();
      page.setDialectType(
      "mysql");
      return page;
      }

    /**

    • 這里全部使用mybatis-autoconfigure 已經自動加載的資源。不手動指定
    • 配置文件和mybatis-boot的配置文件同步
    • @return
      */
      @Bean
      public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
      MybatisSqlSessionFactoryBean mybatisPlus
      = new MybatisSqlSessionFactoryBean();
      mybatisPlus.setDataSource(dataSource);
      mybatisPlus.setVfs(SpringBootVFS.
      class);
      if (StringUtils.hasText(this.properties.getConfigLocation())) {
      mybatisPlus.setConfigLocation(
      this.resourceLoader.getResource(this.properties.getConfigLocation()));
      }
      mybatisPlus.setConfiguration(properties.getConfiguration());
      if (!ObjectUtils.isEmpty(this.interceptors)) {
      mybatisPlus.setPlugins(
      this.interceptors);
      }
      // MP 全局配置,更多內容進入類看注釋
      GlobalConfiguration globalConfig = new GlobalConfiguration();
      globalConfig.setDbType(DBType.MYSQL.name());
      // ID 策略 AUTO->0("數據庫ID自增") INPUT->1(用戶輸入ID") ID_WORKER->2("全局唯一ID") UUID->3("全局唯一ID")
      globalConfig.setIdType(2);
      mybatisPlus.setGlobalConfig(globalConfig);
      MybatisConfiguration mc
      = new MybatisConfiguration();
      mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.
      class);
      mybatisPlus.setConfiguration(mc);
      if (this.databaseIdProvider != null) {
      mybatisPlus.setDatabaseIdProvider(
      this.databaseIdProvider);
      }
      if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
      mybatisPlus.setTypeAliasesPackage(
      this.properties.getTypeAliasesPackage());
      }
      if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
      mybatisPlus.setTypeHandlersPackage(
      this.properties.getTypeHandlersPackage());
      }
      if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
      mybatisPlus.setMapperLocations(
      this.properties.resolveMapperLocations());
      }
      return mybatisPlus;
      }

    /**

    • 注冊一個StatViewServlet
    • @return
      /
      @Bean
      public ServletRegistrationBean DruidStatViewServle(){
      //org.springframework.boot.context.embedded.ServletRegistrationBean提供類的進行注冊.
      ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/
      ");
      //添加初始化參數:initParams
      //白名單:
      // servletRegistrationBean.addInitParameter("allow","127.0.0.1");
      //IP黑名單 (存在共同時,deny優先於allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page.
      // servletRegistrationBean.addInitParameter("deny","192.168.1.73");
      //登錄查看信息的賬號密碼.
      servletRegistrationBean.addInitParameter("loginUsername","root");
      servletRegistrationBean.addInitParameter(
      "loginPassword","root");
      //是否能夠重置數據.
      servletRegistrationBean.addInitParameter("resetEnable","false");
      return servletRegistrationBean;
      }

    /**

    • 注冊一個:filterRegistrationBean
    • @return
      /
      @Bean
      public FilterRegistrationBean druidStatFilter(){
      FilterRegistrationBean filterRegistrationBean
      = new FilterRegistrationBean(new WebStatFilter());
      //添加過濾規則.
      filterRegistrationBean.addUrlPatterns("/
      ");
      //添加不需要忽略的格式信息.
      filterRegistrationBean.addInitParameter("exclusions",".js,.gif,.jpg,.png,.css,.ico,/druid/*");
      return filterRegistrationBean;
      }

}

復制代碼

這里是完整的配置文件,需要注意的是引入的包,別引錯了!

4、還要開啟dao的掃描,很簡單,就是在啟動文件中添加@MapperScan("com.tdx.account_service.dao*"),如下是完整的

到這里,配置算是完成了,運行一下項目是可以運行起來的。

我覺得Mybatis-Plus最好玩得應該是代碼生成器這部分內容,下面是代碼生成器的使用過程

pom.xml上要加點東西

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>

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

MybatisPlusConfig.java
復制代碼
/**
 * Copyright (c) 2011-2016, hubin (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.tdx.account_service.generator;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

/**
*code is far away from bug with the animal protecting

  • ┏┓   ┏┓
    *┏┛┻━━━┛┻┓
    *┃       ┃  
    *┃   ━   ┃
    *┃ ┳┛ ┗┳ ┃
    *┃       ┃
    *┃   ┻   ┃
    *┃       ┃
    *┗━┓   ┏━┛
    *  ┃   ┃神獸保佑
    *  ┃   ┃代碼無BUG!
    *  ┃   ┗━━━┓
    *  ┃       ┣┓
    *  ┃       ┏┛
    *  ┗┓┓┏━┳┓┏┛
    *   ┃┫┫ ┃┫┫
    *   ┗┻┛ ┗┻┛
    *  
  • @Description : MybatisPlus代碼生成器

  • @Author : Liang.Guangqing
  • @Date : Create in 2017/9/19 14:48 
    */
    public class MysqlGenerator {
</span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String packageName="account_service";    <span style="color: #008000">//</span><span style="color: #008000">文件路徑</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String authorName="Liang.Guangqing";     <span style="color: #008000">//</span><span style="color: #008000">作者</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String table="sc_user";                  <span style="color: #008000">//</span><span style="color: #008000">table名字</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String prefix="sc_";                     <span style="color: #008000">//</span><span style="color: #008000">table前綴</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> File file = <span style="color: #0000ff">new</span><span style="color: #000000"> File(packageName);
</span><span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> String path =<span style="color: #000000"> file.getAbsolutePath();

</span><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span><span style="color: #000000"> main(String[] args) {
    </span><span style="color: #008000">//</span><span style="color: #008000"> 自定義需要填充的字段</span>
    List&lt;TableFill&gt; tableFillList = <span style="color: #0000ff">new</span> ArrayList&lt;&gt;<span style="color: #000000">();
    tableFillList.add(</span><span style="color: #0000ff">new</span> TableFill("ASDD_SS"<span style="color: #000000">, FieldFill.INSERT_UPDATE));
    </span><span style="color: #008000">//</span><span style="color: #008000"> 代碼生成器</span>
    AutoGenerator mpg = <span style="color: #0000ff">new</span><span style="color: #000000"> AutoGenerator().setGlobalConfig(
            </span><span style="color: #008000">//</span><span style="color: #008000"> 全局配置</span>
            <span style="color: #0000ff">new</span><span style="color: #000000"> GlobalConfig()
                    .setOutputDir(path</span>+"/src/main/java")<span style="color: #008000">//</span><span style="color: #008000">輸出目錄</span>
                    .setFileOverride(<span style="color: #0000ff">true</span>)<span style="color: #008000">//</span><span style="color: #008000"> 是否覆蓋文件</span>
                    .setActiveRecord(<span style="color: #0000ff">true</span>)<span style="color: #008000">//</span><span style="color: #008000"> 開啟 activeRecord 模式</span>
                    .setEnableCache(<span style="color: #0000ff">false</span>)<span style="color: #008000">//</span><span style="color: #008000"> XML 二級緩存</span>
                    .setBaseResultMap(<span style="color: #0000ff">true</span>)<span style="color: #008000">//</span><span style="color: #008000"> XML ResultMap</span>
                    .setBaseColumnList(<span style="color: #0000ff">true</span>)<span style="color: #008000">//</span><span style="color: #008000"> XML columList</span>
                    .setOpen(<span style="color: #0000ff">false</span>)<span style="color: #008000">//</span><span style="color: #008000">生成后打開文件夾</span>

.setAuthor(authorName)
// 自定義文件命名,注意 %s 會自動填充表實體屬性!
.setMapperName("%sMapper")
.setXmlName(
"%sMapper")
.setServiceName(
"%sService")
.setServiceImplName(
"%sServiceImpl")
.setControllerName(
"%sController")
).setDataSource(
// 數據源配置
new DataSourceConfig()
.setDbType(DbType.MYSQL)
// 數據庫類型
.setTypeConvert(new MySqlTypeConvert() {
// 自定義數據庫表字段類型轉換【可選】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println(
"轉換類型:" + fieldType);
// if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
// return DbColumnType.BOOLEAN;
// }
return super.processTypeConvert(fieldType);
}
})
.setDriverName(
"com.mysql.jdbc.Driver")
.setUsername(
"root")
.setPassword(
"root")
.setUrl(
"jdbc:mysql://127.0.0.1:3306/tdx_shop?characterEncoding=utf8")
).setStrategy(
// 策略配置
new StrategyConfig()
// .setCapitalMode(true)// 全局大寫命名
//.setDbColumnUnderline(true)//全局下划線命名
.setTablePrefix(new String[]{prefix})// 此處可以修改為您的表前綴
.setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
.setInclude(new String[] { table }) // 需要生成的表
.setRestControllerStyle(true)
//.setExclude(new String[]{"test"}) // 排除生成的表
// 自定義實體父類
// .setSuperEntityClass("com.baomidou.demo.TestEntity")
// 自定義實體,公共字段
//.setSuperEntityColumns(new String[]{"test_id"})
.setTableFillList(tableFillList)
// 自定義 mapper 父類
// .setSuperMapperClass("com.baomidou.demo.TestMapper")
// 自定義 service 父類
// .setSuperServiceClass("com.baomidou.demo.TestService")
// 自定義 service 實現類父類
// .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
// 自定義 controller 父類
.setSuperControllerClass("com.tdx."+packageName+".controller.AbstractController")
// 【實體】是否生成字段常量(默認 false)
// public static final String ID = "test_id";
// .setEntityColumnConstant(true)
// 【實體】是否為構建者模型(默認 false)
// public User setName(String name) {this.name = name; return this;}
// .setEntityBuilderModel(true)
// 【實體】是否為lombok模型(默認 false)<a href="https://projectlombok.org/">document</a>
// .setEntityLombokModel(true)
// Boolean類型字段是否移除is前綴處理
// .setEntityBooleanColumnRemoveIsPrefix(true)
// .setRestControllerStyle(true)
// .setControllerMappingHyphenStyle(true)
).setPackageInfo(
// 包配置
new PackageConfig()
//.setModuleName("User")
.setParent("com.tdx."+packageName)// 自定義包路徑
.setController("controller")// 這里是控制器包名,默認 web
.setEntity("entity")
.setMapper(
"dao")
.setService(
"service")
.setServiceImpl(
"service.impl")
//.setXml("mapper")
).setCfg(
// 注入自定義配置,可以在 VM 中使用 cfg.abc 設置的值
new InjectionConfig() {
@Override
public void initMap() {
Map
<String, Object> map = new HashMap<>();
map.put(
"abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
}.setFileOutConfigList(Collections.
<FileOutConfig>singletonList(new FileOutConfig("/templates/mapper.xml.vm") {
// 自定義輸出文件目錄
@Override
public String outputFile(TableInfo tableInfo) {
return path+"/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
}
}))
).setTemplate(
// 關閉默認 xml 生成,調整生成 至 根目錄
new TemplateConfig().setXml(null)
// 自定義模板配置,模板可以參考源碼 /mybatis-plus/src/main/resources/template 使用 copy
// 至您項目 src/main/resources/template 目錄下,模板名稱也可自定義如下配置:
// .setController("...");
// .setEntity("...");
// .setMapper("...");
// .setXml("...");
// .setService("...");
// .setServiceImpl("...");
);

    </span><span style="color: #008000">//</span><span style="color: #008000"> 執行生成</span>

mpg.execute();

    </span><span style="color: #008000">//</span><span style="color: #008000"> 打印注入設置,這里演示模板里面怎么獲取注入內容【可無】</span>
    System.err.println(mpg.getCfg().getMap().get("abc"<span style="color: #000000">));
}

}

復制代碼

文件中修改的內容還是很多的,最主要的還是mysql的連接信息,沒理由你賬號,密碼都錯了還能連得上吧,其次設置一下你生成的模板文件路徑,我這里生成的路徑在上面圖可以看得到,是在com.tdx.account_service下的,注意,xml文件要放在resources下,不然是識別的,說找不到這個方法

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

controller.java.vm

復制代碼
package ${package.Controller};

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

if(${restControllerStyle})

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

else

import org.springframework.stereotype.Controller;

end

if(${superControllerClassPackage})

import ${superControllerClassPackage};

end

import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.common.DatatablesJSON;
import ${package.Entity}.common.JSONResult;
import ${package.Entity}.${entity};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
*code is far away from bug with the animal protecting

  • ┏┓   ┏┓
    *┏┛┻━━━┛┻┓
    *┃       ┃  
    *┃   ━   ┃
    *┃ ┳┛ ┗┳ ┃
    *┃       ┃
    *┃   ┻   ┃
    *┃       ┃
    *┗━┓   ┏━┛
    *  ┃   ┃神獸保佑
    *  ┃   ┃代碼無BUG!
    *  ┃   ┗━━━┓
    *  ┃       ┣┓
    *  ┃       ┏┛
    *  ┗┓┓┏━┳┓┏┛
    *   ┃┫┫ ┃┫┫
    *   ┗┻┛ ┗┻┛
    *  
  • @description : ${entity} 控制器

  •  </span><span style="color: #808080">@author</span><span style="color: #008000"> ${author}
    
  • @since ${date}
    */

if(${restControllerStyle})

@RestController

else

@Controller

end

@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")

if(${superControllerClass})

public class ${table.controllerName} extends ${superControllerClass} {

else

public class ${table.controllerName} {

end

</span><span style="color: #0000ff">private</span> <span style="color: #0000ff">final</span> Logger logger = LoggerFactory.getLogger(${table.controllerName}.<span style="color: #0000ff">class</span><span style="color: #000000">);

@Autowired
</span><span style="color: #0000ff">public</span><span style="color: #000000"> ${table.serviceName} ${table.entityPath}Service;

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * @description : 獲取分頁列表
 * ---------------------------------
 * </span><span style="color: #808080">@author</span><span style="color: #008000"> : ${author}
 * </span><span style="color: #808080">@since</span><span style="color: #008000"> : Create in ${date}
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@RequestMapping(value </span>= "/get${entity}List",method =<span style="color: #000000"> RequestMethod.POST)
</span><span style="color: #0000ff">public</span> Object get${entity}List(${entity} param , @RequestParam(value = "draw",defaultValue = "0"<span style="color: #000000">) Integer draw,
                                    @RequestParam(value </span>= "length"<span style="color: #000000">) Integer length,
                                    @RequestParam(value </span>= "start"<span style="color: #000000">) Integer start) {
        DatatablesJSON</span>&lt;${entity}&gt; resJson=<span style="color: #0000ff">new</span> DatatablesJSON&lt;&gt;<span style="color: #000000">();
        </span><span style="color: #0000ff">try</span><span style="color: #000000"> {
            Integer pageNo</span>=<span style="color: #000000">getPageNo(start,length);
            Page</span>&lt;${entity}&gt; page=<span style="color: #0000ff">new</span> Page&lt;${entity}&gt;<span style="color: #000000">(pageNo,length);
            ${table.entityPath}Service.selectPage(page,</span><span style="color: #0000ff">new</span> EntityWrapper&lt;${entity}&gt;<span style="color: #000000">(param));
            resJson.setDraw(draw</span>++<span style="color: #000000">);
            resJson.setRecordsTotal(page.getTotal());
            resJson.setRecordsFiltered(page.getTotal());
            resJson.setData(page.getRecords());
            resJson.setSuccess(</span><span style="color: #0000ff">true</span><span style="color: #000000">);
        }</span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e){
            resJson.setSuccess(</span><span style="color: #0000ff">false</span><span style="color: #000000">);
            resJson.setError(</span>"異常信息:{"+e.getClass().getName()+"}"<span style="color: #000000">);
            logger.info(</span>"異常信息:{}"+<span style="color: #000000">e.getMessage());
        }
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> resJson;
}

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * @description : 通過id獲取${entity}
 * ---------------------------------
 * </span><span style="color: #808080">@author</span><span style="color: #008000"> : ${author}
 * </span><span style="color: #808080">@since</span><span style="color: #008000"> : Create in ${date}
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@RequestMapping(value </span>= "/get${entity}ById",method =<span style="color: #000000"> RequestMethod.GET)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object get${entity}ById(String id) {
        JSONResult</span>&lt;${entity}&gt; resJson = <span style="color: #0000ff">new</span> JSONResult&lt;&gt;<span style="color: #000000">();
        </span><span style="color: #0000ff">try</span><span style="color: #000000"> {
            ${entity} param</span>=<span style="color: #000000"> ${table.entityPath}Service.selectById(id);
            resJson.setData(param);
            resJson.setSuccess(</span><span style="color: #0000ff">true</span><span style="color: #000000">);
        }</span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e) {
            resJson.setSuccess(</span><span style="color: #0000ff">false</span><span style="color: #000000">);
            resJson.setMessage(</span>"異常信息:{"+e.getClass().getName()+"}"<span style="color: #000000">);
            logger.info(</span>"異常信息:{}"+<span style="color: #000000">e.getMessage());
        }
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> resJson;
}

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * @description : 通過id刪除${entity}
 * ---------------------------------
 * </span><span style="color: #808080">@author</span><span style="color: #008000"> : ${author}
 * </span><span style="color: #808080">@since</span><span style="color: #008000"> : Create in ${date}
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@RequestMapping(value </span>= "/delete${entity}ById",method =<span style="color: #000000"> RequestMethod.GET)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object delete${entity}ById(String id) {
        JSONResult</span>&lt;${entity}&gt; resJson = <span style="color: #0000ff">new</span> JSONResult&lt;&gt;<span style="color: #000000">();
        </span><span style="color: #0000ff">try</span><span style="color: #000000">{
            resJson.setSuccess(${table.entityPath}Service.deleteById(id));
        }</span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e) {
            resJson.setSuccess(</span><span style="color: #0000ff">false</span><span style="color: #000000">);
            resJson.setMessage(</span>"異常信息:{"+e.getClass().getName()+"}"<span style="color: #000000">);
            logger.info(</span>"異常信息:{}"+<span style="color: #000000">e.getMessage());
        }
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> resJson;
}

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * @description : 通過id更新${entity}
 * ---------------------------------
 * </span><span style="color: #808080">@author</span><span style="color: #008000"> : ${author}
 * </span><span style="color: #808080">@since</span><span style="color: #008000"> : Create in ${date}
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@RequestMapping(value </span>= "/update${entity}ById",method =<span style="color: #000000"> RequestMethod.POST)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object update${entity}ById(${entity} param) {
        JSONResult</span>&lt;${entity}&gt; resJson = <span style="color: #0000ff">new</span> JSONResult&lt;&gt;<span style="color: #000000">();
        </span><span style="color: #0000ff">try</span><span style="color: #000000">{
            resJson.setSuccess(${table.entityPath}Service.updateById(param));
        }</span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e) {
            resJson.setSuccess(</span><span style="color: #0000ff">false</span><span style="color: #000000">);
            resJson.setMessage(</span>"異常信息:{"+e.getClass().getName()+"}"<span style="color: #000000">);
            logger.info(</span>"異常信息:{}"+<span style="color: #000000">e.getMessage());
        }
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> resJson;
}

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * @description : 添加${entity}
 * ---------------------------------
 * </span><span style="color: #808080">@author</span><span style="color: #008000"> : ${author}
 * </span><span style="color: #808080">@since</span><span style="color: #008000"> : Create in ${date}
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@RequestMapping(value </span>= "/add${entity}",method =<span style="color: #000000"> RequestMethod.POST)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object add${entity}(${entity} param) {
        JSONResult</span>&lt;${entity}&gt; resJson = <span style="color: #0000ff">new</span> JSONResult&lt;&gt;<span style="color: #000000">();
        </span><span style="color: #0000ff">try</span><span style="color: #000000">{
            resJson.setSuccess(${table.entityPath}Service.insert(param));
        }</span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e) {
            resJson.setSuccess(</span><span style="color: #0000ff">false</span><span style="color: #000000">);
            resJson.setMessage(</span>"異常信息:{"+e.getClass().getName()+"}"<span style="color: #000000">);
            logger.info(</span>"異常信息:{}"+<span style="color: #000000">e.getMessage());
        }
        </span><span style="color: #0000ff">return</span><span style="color: #000000"> resJson;
}

}

復制代碼

除了這個文件,其他代碼模板我都是按照官網那樣的,這里引用3個外部的文件,有AbstractController.java(控制器基類)、DatatablesJSON.java和JSONResult.java,然后這些文件又引用了其他文件,我懵逼了,怎么文件這么多啊,看來如果全部都貼上來得多占地方啊,所以我選擇相信碼雲,如果需要請在碼雲上按照少的文件下載,碼雲地址需要注意的是,我的模板是直接代替了mybatis-plus.jar中的templates目錄。

 

最后就到了測試過程

下面的代碼段都是放在Controller文件里面,然后啟動程序,對應端口,請求方法。測試的話是需要按照自己的實體類操作的,所以僅供參考。

 

復制代碼
    /**
     * 分頁 PAGE
     */
    @GetMapping("/test")
    public Page<User> test() {
        return userService.selectPage(new Page<User>(0, 12));
    }
</span><span style="color: #008000">/**</span><span style="color: #008000">
 * AR 部分測試
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@GetMapping(</span>"/test1"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span> Page&lt;User&gt;<span style="color: #000000"> test1() {
    User user </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> User();
    System.err.println(</span>"刪除所有:" + user.delete(<span style="color: #0000ff">null</span><span style="color: #000000">));
    </span><span style="color: #008000">//</span><span style="color: #008000">user.setId(2017091801L);</span>
    user.setAccout("test"+num++<span style="color: #000000">);
    user.setType(</span>"test"<span style="color: #000000">);
    user.setCreateTime(</span><span style="color: #0000ff">new</span><span style="color: #000000"> Date());
    user.setPhone(</span>"13111110000"<span style="color: #000000">);
    user.setPassword(</span>"123456"<span style="color: #000000">);
    user.setNickname(</span>"guangqing"+2*num++<span style="color: #000000">);
    user.insert();
    System.err.println(</span>"查詢插入結果:" +<span style="color: #000000"> user.selectById().toString());
    </span><span style="color: #008000">//</span><span style="color: #008000">user.setNickname("mybatis-plus-ar");</span>
    System.err.println("更新:" +<span style="color: #000000"> user.updateById());
    </span><span style="color: #0000ff">return</span> user.selectPage(<span style="color: #0000ff">new</span> Page&lt;User&gt;(0, 12), <span style="color: #0000ff">null</span><span style="color: #000000">);
}

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * 增刪改查 CRUD
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@GetMapping(</span>"/test2"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> User test2() {
    User user </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> User();
    user.setId(</span>123456L<span style="color: #000000">);
    user.setAccout(</span>"test"<span style="color: #000000">);
    user.setType(</span>"test"<span style="color: #000000">);
    user.setCreateTime(</span><span style="color: #0000ff">new</span><span style="color: #000000"> Date());
    user.setPhone(</span>"13111110000"<span style="color: #000000">);
    user.setPassword(</span>"123456"<span style="color: #000000">);
    user.setNickname(</span>"guangqing"<span style="color: #000000">);
    System.err.println(</span>"刪除一條數據:" + userService.deleteById(1L<span style="color: #000000">));
    System.err.println(</span>"插入一條數據:" +<span style="color: #000000"> userService.insert(user));
    User user2 </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> User();
    user.setId(</span>223456L<span style="color: #000000">);
    user.setAccout(</span>"test2"<span style="color: #000000">);
    user.setType(</span>"test"<span style="color: #000000">);
    user.setCreateTime(</span><span style="color: #0000ff">new</span><span style="color: #000000"> Date());
    user.setPhone(</span>"13111110000"<span style="color: #000000">);
    user.setPassword(</span>"123456"<span style="color: #000000">);
    user.setNickname(</span>"guangqing"<span style="color: #000000">);
    </span><span style="color: #0000ff">boolean</span> result =<span style="color: #000000"> userService.insert(user);
    </span><span style="color: #008000">//</span><span style="color: #008000"> 自動回寫的ID</span>
    Long id =<span style="color: #000000"> user.getId();
    System.err.println(</span>"插入一條數據:" + result + ", 插入信息:" +<span style="color: #000000"> user.toString());
    System.err.println(</span>"查詢:" +<span style="color: #000000"> userService.selectById(id).toString());
    Page</span>&lt;User&gt; userListPage = userService.selectPage(<span style="color: #0000ff">new</span> Page&lt;User&gt;(1, 5), <span style="color: #0000ff">new</span> EntityWrapper&lt;&gt;(<span style="color: #0000ff">new</span><span style="color: #000000"> User()));
    System.err.println(</span>"total=" + userListPage.getTotal() + ", current list size=" +<span style="color: #000000"> userListPage.getRecords().size());
    </span><span style="color: #0000ff">return</span> userService.selectById(1L<span style="color: #000000">);
}

@GetMapping(</span>"testSelect"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object testSelect() {
    Integer start </span>= 0<span style="color: #000000">;
    Integer length </span>=10<span style="color: #000000">;
    User param </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> User();
    </span><span style="color: #008000">//</span><span style="color: #008000">param.setNickname("guangqing2");</span>
    Integer pageNo=<span style="color: #000000">getPageNo(start,length);
    Page</span>&lt;User&gt; page =<span style="color: #0000ff">new</span> Page&lt;User&gt;<span style="color: #000000">(pageNo,length);
    EntityWrapper</span>&lt;User&gt; ew = <span style="color: #0000ff">new</span> EntityWrapper&lt;User&gt;<span style="color: #000000">();
    ew.setEntity(param);
    ew.where(</span>"password={0}","123456"<span style="color: #000000">)
            .like(</span>"nickname","guangqing"<span style="color: #000000">)
            .ge(</span>"create_time","2017-09-21 15:50:00"<span style="color: #000000">);
    userService.selectPage(page, ew);
    DatatablesJSON</span>&lt;User&gt; resJson= <span style="color: #0000ff">new</span> DatatablesJSON&lt;&gt;<span style="color: #000000">();
    </span><span style="color: #008000">//</span><span style="color: #008000">resJson.setDraw(draw++);</span>

resJson.setRecordsTotal(page.getTotal());
resJson.setRecordsFiltered(page.getTotal());
resJson.setData(page.getRecords());
return resJson;
}

@GetMapping(</span>"/selectsql"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object getUserBySql() {
    JSONObject result </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> JSONObject();
    result.put(</span>"records"<span style="color: #000000">, userService.selectListBySQL());
    </span><span style="color: #0000ff">return</span><span style="color: #000000"> result;
}

</span><span style="color: #008000">/**</span><span style="color: #008000">
 * 7、分頁 size 一頁顯示數量  current 當前頁碼
 * 方式一:</span><span style="color: #008000; text-decoration: underline">http://localhost</span><span style="color: #008000">:8080/user/page?size=1&amp;current=1&lt;br&gt;
 * 方式二:</span><span style="color: #008000; text-decoration: underline">http://localhost</span><span style="color: #008000">:8080/user/pagehelper?size=1&amp;current=1&lt;br&gt;
 </span><span style="color: #008000">*/</span>

<span style="color: #008000">//</span><span style="color: #008000"> 參數模式分頁</span>
@GetMapping("/page"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object page(Page page) {
    </span><span style="color: #0000ff">return</span><span style="color: #000000"> userService.selectPage(page);
}

</span><span style="color: #008000">//</span><span style="color: #008000"> ThreadLocal 模式分頁</span>
@GetMapping("/pagehelper"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span><span style="color: #000000"> Object pagehelper(Page page) {
    PageHelper.setPagination(page);
    page.setRecords(userService.selectList(</span><span style="color: #0000ff">null</span><span style="color: #000000">));
    page.setTotal(PageHelper.freeTotal());</span><span style="color: #008000">//</span><span style="color: #008000">獲取總數並釋放資源 也可以 PageHelper.getTotal()</span>
    <span style="color: #0000ff">return</span><span style="color: #000000"> page;
}


</span><span style="color: #008000">/**</span><span style="color: #008000">
 * 測試事物
 * </span><span style="color: #008000; text-decoration: underline">http://localhost</span><span style="color: #008000">:8080/user/test_transactional&lt;br&gt;
 * 訪問如下並未發現插入數據說明事物可靠!!&lt;br&gt;
 * </span><span style="color: #008000; text-decoration: underline">http://localhost</span><span style="color: #008000">:8080/user/test&lt;br&gt;
 * &lt;br&gt;
 * 啟動  Application 加上 @EnableTransactionManagement 注解其實可無默認貌似就開啟了&lt;br&gt;
 * 需要事物的方法加上 @Transactional 必須的哦!!
 </span><span style="color: #008000">*/</span><span style="color: #000000">
@Transactional
@GetMapping(</span>"/test_transactional"<span style="color: #000000">)
</span><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span><span style="color: #000000"> testTransactional() {
    </span><span style="color: #008000">//</span><span style="color: #008000">userService.insert(new User(1000L, "測試事物", 16, 3));</span>
    System.out.println(" 這里手動拋出異常,自動回滾數據"<span style="color: #000000">);
    </span><span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span><span style="color: #000000"> RuntimeException();
}</span></pre>
復制代碼

 

這么多的測試,我覺得最有趣的是條件構造器,在官網上有更齊全的,而我這里是按照我自己的需求寫的。

 

最后謝謝大家的觀看,寫博客經驗不足,寫得不好請見諒,如果能給你帶來幫助請點個贊,若遇到不明白的,或者我有寫錯的地方請提出,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM