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内容部分了
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 { 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/" rel="external nofollow" >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; } /** * 7、分页 size 一页显示数量 current 当前页码 * 方式一:http://localhost:8080/user/page?size=1¤t=1<br> * 方式二:http://localhost:8080/user/pagehelper?size=1¤t=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(); }
这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。
最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!也希望大家多多支持。
上一篇: 海尔走在新长征路上
下一篇: css3实现画半圆弧线的示例代码