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

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

application.yml

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 配置文件的。注意一下红字的内容,基本没问题了。

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

接着就是 MybatisPlusConfig 内容部分了

1
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();
}
}
 

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

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、代码生成器的配置文件

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 {
</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">static</span> String packageName="account_service";    <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">文件路径</span>
<span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">static</span> String authorName="Liang.Guangqing";     <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">作者</span>
<span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">static</span> String table="sc_user";                  <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">table名字</span>
<span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">static</span> String prefix="sc_";                     <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">table前缀</span>
<span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">static</span> File file = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> File(packageName);
</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">static</span> String path =<span style="color: rgba(0, 0, 0, 1)"> file.getAbsolutePath();

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 自定义需要填充的字段</span>
    List&lt;TableFill&gt; tableFillList = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;&gt;<span style="color: rgba(0, 0, 0, 1)">();
    tableFillList.add(</span><span style="color: rgba(0, 0, 255, 1)">new</span> TableFill("ASDD_SS"<span style="color: rgba(0, 0, 0, 1)">, FieldFill.INSERT_UPDATE));
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 代码生成器</span>
    AutoGenerator mpg = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> AutoGenerator().setGlobalConfig(
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 全局配置</span>
            <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> GlobalConfig()
                    .setOutputDir(path</span>+"/src/main/java")<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">输出目录</span>
                    .setFileOverride(<span style="color: rgba(0, 0, 255, 1)">true</span>)<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 是否覆盖文件</span>
                    .setActiveRecord(<span style="color: rgba(0, 0, 255, 1)">true</span>)<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 开启 activeRecord 模式</span>
                    .setEnableCache(<span style="color: rgba(0, 0, 255, 1)">false</span>)<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> XML 二级缓存</span>
                    .setBaseResultMap(<span style="color: rgba(0, 0, 255, 1)">true</span>)<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> XML ResultMap</span>
                    .setBaseColumnList(<span style="color: rgba(0, 0, 255, 1)">true</span>)<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> XML columList</span>
                    .setOpen(<span style="color: rgba(0, 0, 255, 1)">false</span>)<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">生成后打开文件夹</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: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 执行生成</span>

mpg.execute();

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 打印注入设置,这里演示模板里面怎么获取注入内容【可无】</span>
    System.err.println(mpg.getCfg().getMap().get("abc"<span style="color: rgba(0, 0, 0, 1)">));
}

}

文件中修改的内容还是很多的,最主要的还是 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: rgba(128, 128, 128, 1)">@author</span><span style="color: rgba(0, 128, 0, 1)"> ${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
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> ${table.serviceName} ${table.entityPath}Service;

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

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

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * @description : 通过id删除${entity}
 * ---------------------------------
 * </span><span style="color: rgba(128, 128, 128, 1)">@author</span><span style="color: rgba(0, 128, 0, 1)"> : ${author}
 * </span><span style="color: rgba(128, 128, 128, 1)">@since</span><span style="color: rgba(0, 128, 0, 1)"> : Create in ${date}
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@RequestMapping(value </span>= "/delete${entity}ById",method =<span style="color: rgba(0, 0, 0, 1)"> RequestMethod.GET)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object delete${entity}ById(String id) {
        JSONResult</span>&lt;${entity}&gt; resJson = <span style="color: rgba(0, 0, 255, 1)">new</span> JSONResult&lt;&gt;<span style="color: rgba(0, 0, 0, 1)">();
        </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
            resJson.setSuccess(${table.entityPath}Service.deleteById(id));
        }</span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
            resJson.setSuccess(</span><span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">);
            resJson.setMessage(</span>"异常信息:{"+e.getClass().getName()+"}"<span style="color: rgba(0, 0, 0, 1)">);
            logger.info(</span>"异常信息:{}"+<span style="color: rgba(0, 0, 0, 1)">e.getMessage());
        }
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> resJson;
}

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

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * @description : 添加${entity}
 * ---------------------------------
 * </span><span style="color: rgba(128, 128, 128, 1)">@author</span><span style="color: rgba(0, 128, 0, 1)"> : ${author}
 * </span><span style="color: rgba(128, 128, 128, 1)">@since</span><span style="color: rgba(0, 128, 0, 1)"> : Create in ${date}
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@RequestMapping(value </span>= "/add${entity}",method =<span style="color: rgba(0, 0, 0, 1)"> RequestMethod.POST)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object add${entity}(${entity} param) {
        JSONResult</span>&lt;${entity}&gt; resJson = <span style="color: rgba(0, 0, 255, 1)">new</span> JSONResult&lt;&gt;<span style="color: rgba(0, 0, 0, 1)">();
        </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">{
            resJson.setSuccess(${table.entityPath}Service.insert(param));
        }</span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
            resJson.setSuccess(</span><span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">);
            resJson.setMessage(</span>"异常信息:{"+e.getClass().getName()+"}"<span style="color: rgba(0, 0, 0, 1)">);
            logger.info(</span>"异常信息:{}"+<span style="color: rgba(0, 0, 0, 1)">e.getMessage());
        }
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> 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: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * AR 部分测试
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@GetMapping(</span>"/test1"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> Page&lt;User&gt;<span style="color: rgba(0, 0, 0, 1)"> test1() {
    User user </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> User();
    System.err.println(</span>"删除所有:" + user.delete(<span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">));
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">user.setId(2017091801L);</span>
    user.setAccout("test"+num++<span style="color: rgba(0, 0, 0, 1)">);
    user.setType(</span>"test"<span style="color: rgba(0, 0, 0, 1)">);
    user.setCreateTime(</span><span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Date());
    user.setPhone(</span>"13111110000"<span style="color: rgba(0, 0, 0, 1)">);
    user.setPassword(</span>"123456"<span style="color: rgba(0, 0, 0, 1)">);
    user.setNickname(</span>"guangqing"+2*num++<span style="color: rgba(0, 0, 0, 1)">);
    user.insert();
    System.err.println(</span>"查询插入结果:" +<span style="color: rgba(0, 0, 0, 1)"> user.selectById().toString());
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">user.setNickname("mybatis-plus-ar");</span>
    System.err.println("更新:" +<span style="color: rgba(0, 0, 0, 1)"> user.updateById());
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> user.selectPage(<span style="color: rgba(0, 0, 255, 1)">new</span> Page&lt;User&gt;(0, 12), <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">);
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 增删改查 CRUD
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@GetMapping(</span>"/test2"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> User test2() {
    User user </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> User();
    user.setId(</span>123456L<span style="color: rgba(0, 0, 0, 1)">);
    user.setAccout(</span>"test"<span style="color: rgba(0, 0, 0, 1)">);
    user.setType(</span>"test"<span style="color: rgba(0, 0, 0, 1)">);
    user.setCreateTime(</span><span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Date());
    user.setPhone(</span>"13111110000"<span style="color: rgba(0, 0, 0, 1)">);
    user.setPassword(</span>"123456"<span style="color: rgba(0, 0, 0, 1)">);
    user.setNickname(</span>"guangqing"<span style="color: rgba(0, 0, 0, 1)">);
    System.err.println(</span>"删除一条数据:" + userService.deleteById(1L<span style="color: rgba(0, 0, 0, 1)">));
    System.err.println(</span>"插入一条数据:" +<span style="color: rgba(0, 0, 0, 1)"> userService.insert(user));
    User user2 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> User();
    user.setId(</span>223456L<span style="color: rgba(0, 0, 0, 1)">);
    user.setAccout(</span>"test2"<span style="color: rgba(0, 0, 0, 1)">);
    user.setType(</span>"test"<span style="color: rgba(0, 0, 0, 1)">);
    user.setCreateTime(</span><span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Date());
    user.setPhone(</span>"13111110000"<span style="color: rgba(0, 0, 0, 1)">);
    user.setPassword(</span>"123456"<span style="color: rgba(0, 0, 0, 1)">);
    user.setNickname(</span>"guangqing"<span style="color: rgba(0, 0, 0, 1)">);
    </span><span style="color: rgba(0, 0, 255, 1)">boolean</span> result =<span style="color: rgba(0, 0, 0, 1)"> userService.insert(user);
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 自动回写的ID</span>
    Long id =<span style="color: rgba(0, 0, 0, 1)"> user.getId();
    System.err.println(</span>"插入一条数据:" + result + ", 插入信息:" +<span style="color: rgba(0, 0, 0, 1)"> user.toString());
    System.err.println(</span>"查询:" +<span style="color: rgba(0, 0, 0, 1)"> userService.selectById(id).toString());
    Page</span>&lt;User&gt; userListPage = userService.selectPage(<span style="color: rgba(0, 0, 255, 1)">new</span> Page&lt;User&gt;(1, 5), <span style="color: rgba(0, 0, 255, 1)">new</span> EntityWrapper&lt;&gt;(<span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> User()));
    System.err.println(</span>"total=" + userListPage.getTotal() + ", current list size=" +<span style="color: rgba(0, 0, 0, 1)"> userListPage.getRecords().size());
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> userService.selectById(1L<span style="color: rgba(0, 0, 0, 1)">);
}

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

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

@GetMapping(</span>"/selectsql"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object getUserBySql() {
    JSONObject result </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> JSONObject();
    result.put(</span>"records"<span style="color: rgba(0, 0, 0, 1)">, userService.selectListBySQL());
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result;
}

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 7、分页 size 一页显示数量  current 当前页码
 * 方式一:</span><span style="color: rgba(0, 128, 0, 1); text-decoration: underline">http://localhost</span><span style="color: rgba(0, 128, 0, 1)">:8080/user/page?size=1&amp;current=1&lt;br&gt;
 * 方式二:</span><span style="color: rgba(0, 128, 0, 1); text-decoration: underline">http://localhost</span><span style="color: rgba(0, 128, 0, 1)">:8080/user/pagehelper?size=1&amp;current=1&lt;br&gt;
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>

<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 参数模式分页</span>
@GetMapping("/page"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object page(Page page) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> userService.selectPage(page);
}

</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> ThreadLocal 模式分页</span>
@GetMapping("/pagehelper"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object pagehelper(Page page) {
    PageHelper.setPagination(page);
    page.setRecords(userService.selectList(</span><span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">));
    page.setTotal(PageHelper.freeTotal());</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取总数并释放资源 也可以 PageHelper.getTotal()</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> page;
}


</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 测试事物
 * </span><span style="color: rgba(0, 128, 0, 1); text-decoration: underline">http://localhost</span><span style="color: rgba(0, 128, 0, 1)">:8080/user/test_transactional&lt;br&gt;
 * 访问如下并未发现插入数据说明事物可靠!!&lt;br&gt;
 * </span><span style="color: rgba(0, 128, 0, 1); text-decoration: underline">http://localhost</span><span style="color: rgba(0, 128, 0, 1)">:8080/user/test&lt;br&gt;
 * &lt;br&gt;
 * 启动  Application 加上 @EnableTransactionManagement 注解其实可无默认貌似就开启了&lt;br&gt;
 * 需要事物的方法加上 @Transactional 必须的哦!!
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@Transactional
@GetMapping(</span>"/test_transactional"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> testTransactional() {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">userService.insert(new User(1000L, "测试事物", 16, 3));</span>
    System.out.println(" 这里手动抛出异常,自动回滚数据"<span style="color: rgba(0, 0, 0, 1)">);
    </span><span style="color: rgba(0, 0, 255, 1)">throw</span> <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> RuntimeException();
}</span></pre>

 

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

 

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