spring boot整合mybatis+mybatis-plus

Spring boot對於我來講是一個剛接觸的新東西,學習過程當中,發現這東西仍是很容易上手的,Spring boot沒配置時會默認使用Spring data jpa,這東西能夠說一個極簡潔的工具,但是我仍是比較喜歡用mybatis,工具是沒有最好的,只有這合適本身的。css

說到mybatis,最近有一個很好用的工具--------mybatis-Plus(官網),如今更新的版本是2.1.2,這裏使用的也是這個版本。我比較喜歡的功能是代碼生成器,條件構造器,這樣就能夠更容易的去開發了。java

mybatisPlus官網上是有Spring boot整個的例子的,我也跟着它走了一篇,結果,程序沒跑起來,後來才知道demo用的H2 database,和mysql根本不是同同樣東西,因此各位想要整合mybatisPlus,能夠不看官網的,能夠少走彎路。node

下面就是整合的過程mysql

一、首先要把須要的jar文件都弄過來,pom.xml須要的東西以下git

pom.xml(不完整)web

<!-- mybatis-plus begin -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatisplus-spring-boot-starter</artifactId>
    <version>1.0.5</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>2.1.8</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.6</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>

二、添加mybatis相關的配置,如帳號、密碼等。這裏我使用了application.yml來配。redis

application.ymlspring

server:
    port: 8080
#spring
spring:
aop:
proxy-target-class: true

#DATABASE CONFIG 注意這裏連得是sql server
datasource:
druid:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: tdxuser
password: ${MSSQL_PASSWORD:tdxgps}
url: jdbc:sqlserver://${MSSQL_HOST:192.168.2.77:5609};databaseName=TDXDB
initial-size: 1
max-active: 20
min-idle: 1
max-wait: 60000
validation-query: select 'x'
validationQueryTimeout: 5
test-on-borrow: false
test-on-return: false
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
filters: log4j
filter:
stat:
enabled: true
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
#db-type: sqlserver
slf4j:
enabled: true
connection-log-enabled: true
connection-close-after-log-enabled: true
connection-commit-after-log-enabled: true
connection-connect-after-log-enabled: true
connection-connect-before-log-enabled: true
connection-log-error-enabled: true
data-source-log-enabled: true
result-set-log-enabled: true
statement-log-enabled: true
wall:
enabled: true
config:
alter-table-allow: false
truncate-allow: false
drop-table-allow: false
#是否容許非以上基本語句的其餘語句,缺省關閉,經過這個選項就可以屏蔽DDL
none-base-statement-allow: false
#檢查UPDATE語句是否無where條件,這是有風險的,但不是SQL注入類型的風險
update-where-none-check: true
#SELECT ... INTO OUTFILE 是否容許,這個是mysql注入攻擊的常見手段,缺省是禁止的
select-into-outfile-allow: false
#是否容許調用Connection.getMetadata方法,這個方法調用會暴露數據庫的表信息
metadata-allow: true
#容許多條sql一塊兒執行
multiStatementAllow: true
#對被認爲是攻擊的SQL進行LOG.error輸出
log-violation: true
#對被認爲是攻擊的SQL拋出SQLExcepton
throw-exception: true
#db-type: mysql
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
#你能夠配置principalSessionName,使得druid可以知道當前的cookie的用戶是誰
#principal-cookie-name: admin
#你能夠配置principalSessionName,使得druid可以知道當前的session的用戶是誰
#principal-session-name: admin
#設置profileEnable可以監控單個url調用的sql列表。
profile-enable: true
#session統計功能
session-stat-enable: false
#最大session數
session-stat-max-count: 100000
stat-view-servlet:
#allow: ${GATEWAY_HOST:172.26.114.241}
enabled: true
login-username: ${DRUID_USER:admin}
login-password: ${DRUID_PWD:admin}
url-pattern: /druid/*
#容許清除記錄
reset-enable: false
aop-patterns: com.tdx.account_service.service.*

# Redis配置
redis:
#集羣模式
#cluster:
# nodes:
# - 39.XXX.XX.69:6661
# - 39.XXX.XX.69:6662
# - 39.XXX.XX.69:6663
# - 39.XXX.XX.69:6664
# - 39.XXX.XX.69:6665
# - 39.XXX.XX.69:6666
#單機模式
host: ${REDIS_HOST:192.168.2.18}
port: ${REDIS_PORT:7006}
password: ${REDIS_PASSWORD:root}
#鏈接超時時間(毫秒)
timeout: 10000
pool:
max-idle: 20
min-idle: 5
max-active: 20
max-wait: 2

#mybatis
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
#實體掃描,多個package用逗號或者分號分隔
typeAliasesPackage: com.tdx.account_service.entity
global-config:
#主鍵類型 0:"數據庫ID自增", 1:"用戶輸入ID",2:"全局惟一ID (數字類型惟一ID)", 3:"全局惟一ID UUID";
id-type: 2
#字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: 2
#駝峯下劃線轉換
db-column-underline: true
#刷新mapper 調試神器
refresh-mapper: true
#數據庫大寫下劃線轉換
#capital-mode: true
#序列接口實現類配置
#key-generator: com.baomidou.springboot.xxx
#邏輯刪除配置(下面3個配置)
logic-delete-value: 0
logic-not-delete-value: 1
#自定義SQL注入器
#sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定義填充策略接口實現
#meta-object-handler: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true
cache-enabled: false

#logging
logging:
level: warn

 

配置的東西和咱們之前用mybatis配置能夠說差很少,但spring boot是沒有xml配置文件的。注意一下紅字的內容,基本沒問題了。sql

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

接着就是MybatisPlusConfig內容部分了

MybatisPlusProperties.java
package com.tdx.account_service.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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.spring.MybatisSqlSessionFactoryBean;
import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
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.ConfigurationProperties;
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;

/**
* 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
public class MybatisPlusConfig {

/***
* plus 的性能優化
* @return
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
/*<!-- SQL 執行性能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 -->*/
performanceInterceptor.setMaxTime(1000);
/*<!--SQL是否格式化 默認false-->*/
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}

/**
* @Description : mybatis-plus分頁插件
* ---------------------------------
* @Author : Liang.Guangqing
* @Date : Create in 2017/9/19 13:59
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}


/**
* @Description : druid注入
* ---------------------------------
* @Author : Liang.Guangqing
* @Date : Create in 2018/1/3 17:38
*/
@Bean
@ConfigurationProperties("spring.datasource.druid." )
public DataSource dataSource() {
return DruidDataSourceBuilder
.create()
.build();
}

}
 

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

四、還要開啓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>

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

MysqlGenerator.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 {

    private static String packageName="account_service";    //文件路徑
    private static String authorName="Liang.Guangqing";     //做者
    private static String table="sc_user";                  //table名字
    private static String prefix="sc_";                     //table前綴
    private static File file = new File(packageName);
    private static String path = file.getAbsolutePath();

    public static void main(String[] args) {
        // 自定義須要填充的字段
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
                // 全局配置
                new GlobalConfig()
                        .setOutputDir(path+"/src/main/java")//輸出目錄
                        .setFileOverride(true)// 是否覆蓋文件
                        .setActiveRecord(true)// 開啓 activeRecord 模式
                        .setEnableCache(false)// XML 二級緩存
                        .setBaseResultMap(true)// XML ResultMap
                        .setBaseColumnList(true)// XML columList
                        .setOpen(false)//生成後打開文件夾
                        .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("...");
        );

        // 執行生成
        mpg.execute();

        // 打印注入設置,這裏演示模板裏面怎麼獲取注入內容【可無】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }

}

文件中修改的內容仍是不少的,最主要的仍是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} 控制器
 *   ---------------------------------
 *      @author ${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
    private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

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

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

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

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

    /**
     * @description : 添加${entity}
     * ---------------------------------
     * @author : ${author}
     * @since : Create in ${date}
     */
    @RequestMapping(value = "/add${entity}",method = RequestMethod.POST)
    public Object add${entity}(${entity} param) {
            JSONResult<${entity}> resJson = new JSONResult<>();
            try{
                resJson.setSuccess(${table.entityPath}Service.insert(param));
            }catch (Exception e) {
                resJson.setSuccess(false);
                resJson.setMessage("異常信息:{"+e.getClass().getName()+"}");
                logger.info("異常信息:{}"+e.getMessage());
            }
            return 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));
    }

    /**
     * AR 部分測試
     */
    @GetMapping("/test1")
    public Page<User> test1() {
        User user = new User();
        System.err.println("刪除全部:" + user.delete(null));
        //user.setId(2017091801L);
        user.setAccout("test"+num++);
        user.setType("test");
        user.setCreateTime(new Date());
        user.setPhone("13111110000");
        user.setPassword("123456");
        user.setNickname("guangqing"+2*num++);
        user.insert();
        System.err.println("查詢插入結果:" + user.selectById().toString());
        //user.setNickname("mybatis-plus-ar");
        System.err.println("更新:" + user.updateById());
        return user.selectPage(new Page<User>(0, 12), null);
    }

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

    @GetMapping("testSelect")
    public Object testSelect() {
        Integer start = 0;
        Integer length =10;
        User param = new User();
        //param.setNickname("guangqing2");
        Integer pageNo=getPageNo(start,length);
        Page<User> page =new Page<User>(pageNo,length);
        EntityWrapper<User> ew = new EntityWrapper<User>();
        ew.setEntity(param);
        ew.where("password={0}","123456")
                .like("nickname","guangqing")
                .ge("create_time","2017-09-21 15:50:00");
        userService.selectPage(page, ew);
        DatatablesJSON<User> resJson= new DatatablesJSON<>();
        //resJson.setDraw(draw++);
        resJson.setRecordsTotal(page.getTotal());
        resJson.setRecordsFiltered(page.getTotal());
        resJson.setData(page.getRecords());
        return resJson;
    }


    @GetMapping("/selectsql")
    public Object getUserBySql() {
        JSONObject result = new JSONObject();
        result.put("records", userService.selectListBySQL());
        return result;
    }

    /**
     * 七、分頁 size 一頁顯示數量  current 當前頁碼
     * 方式一:http://localhost:8080/user/page?size=1&current=1<br>
     * 方式二:http://localhost:8080/user/pagehelper?size=1&current=1<br>
     */

    // 參數模式分頁
    @GetMapping("/page")
    public Object page(Page page) {
        return userService.selectPage(page);
    }

    // ThreadLocal 模式分頁
    @GetMapping("/pagehelper")
    public Object pagehelper(Page page) {
        PageHelper.setPagination(page);
        page.setRecords(userService.selectList(null));
        page.setTotal(PageHelper.freeTotal());//獲取總數並釋放資源 也能夠 PageHelper.getTotal()
        return page;
    }


    /**
     * 測試事物
     * http://localhost:8080/user/test_transactional<br>
     * 訪問以下並未發現插入數聽說明事物可靠!!<br>
     * http://localhost:8080/user/test<br>
     * <br>
     * 啓動  Application 加上 @EnableTransactionManagement 註解其實可無默認貌似就開啓了<br>
     * 須要事物的方法加上 @Transactional 必須的哦!!
     */
    @Transactional
    @GetMapping("/test_transactional")
    public void testTransactional() {
        //userService.insert(new User(1000L, "測試事物", 16, 3));
        System.out.println(" 這裏手動拋出異常,自動回滾數據");
        throw new RuntimeException();
    }

 

這麼多的測試,我以爲最有趣的是條件構造器,在官網上有更齊全的,而我這裏是按照我本身的需求寫的。

 

最後謝謝你們的觀看,寫博客經驗不足,寫得很差請見諒,若是能給你帶來幫助請點個贊,若遇到不明白的,或者我有寫錯的地方請提出,謝謝!

相關文章
相關標籤/搜索