Spring boot對(duì)于我來(lái)說(shuō)是一個(gè)剛接觸的新東西,學(xué)習(xí)過(guò)程中,發(fā)現(xiàn)這東西還是很容易上手的,Spring boot沒(méi)配置時(shí)會(huì)默認(rèn)使用Spring data jpa,這東西可以說(shuō)一個(gè)極簡(jiǎn)潔的工具,可是我還是比較喜歡用mybatis,工具是沒(méi)有最好的,只有這合適自己的。
發(fā)展壯大離不開(kāi)廣大客戶長(zhǎng)期以來(lái)的信賴與支持,我們將始終秉承“誠(chéng)信為本、服務(wù)至上”的服務(wù)理念,堅(jiān)持“二合一”的優(yōu)良服務(wù)模式,真誠(chéng)服務(wù)每家企業(yè),認(rèn)真做好每個(gè)細(xì)節(jié),不斷完善自我,成就企業(yè),實(shí)現(xiàn)共贏。行業(yè)涉及成都茶藝設(shè)計(jì)等,在網(wǎng)站建設(shè)公司、全網(wǎng)營(yíng)銷推廣、WAP手機(jī)網(wǎng)站、VI設(shè)計(jì)、軟件開(kāi)發(fā)等項(xiàng)目上具有豐富的設(shè)計(jì)經(jīng)驗(yàn)。
說(shuō)到mybatis,最近有一個(gè)很好用的工具--------mybatis-Plus(官網(wǎng)),現(xiàn)在更新的版本是2.1.2,這里使用的也是這個(gè)版本。我比較喜歡的功能是代碼生成器,條件構(gòu)造器,這樣就可以更容易的去開(kāi)發(fā)了。
mybatisPlus官網(wǎng)上是有Spring boot整個(gè)的例子的,我也跟著它走了一篇,結(jié)果,程序沒(méi)跑起來(lái),后來(lái)才知道demo用的H2 database,和MySQL根本不是同一樣?xùn)|西,所以各位想要整合mybatisPlus,可以不看官網(wǎng)的,可以少走彎路。
下面就是整合的過(guò)程
1、首先要把需要的jar文件都弄過(guò)來(lái),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阿里巴巴數(shù)據(jù)庫(kù)連接池 --> <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相關(guān)的配置,如賬號(hào)、密碼等。這里我使用了application.yml來(lái)配。
application.yml
server: port: 8080 #spring spring: devtools: restart: enabled: true #這里是為了熱部署的,與mybatis是無(wú)關(guān)的 #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.*中可能會(huì)出現(xiàn)找到的問(wèn)題,這里把他放在resource下的mapper中 #實(shí)體掃描,多個(gè)package用逗號(hào)或者分號(hào)分隔 typeAliasesPackage: com.tdx.account_service.entity #這里是實(shí)體類的位置 configuration: map-underscore-to-camel-case: true cache-enabled: false #logging logging: level: warn
配置的東西和我們以前用mybatis配置可以說(shuō)差不多,但spring boot是沒(méi)有xml配置文件的。注意一下紅字的內(nèi)容,基本沒(méi)問(wèn)題了。
3、mybatis-Plus配置文件------MybatisPlusConfig,首先上圖說(shuō)明一下文件路徑。其中MybatisPlusConfig是放在config文件夾內(nèi),而xml文件是放在resouces下mapper中。
接著就是MybatisPlusConfig內(nèi)容部分了
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 * ┏┓ ┏┓ * ┏┛┻━━━┛┻┓ * ┃ ┃ * ┃ ━ ┃ * ┃ ┳┛ ┗┳ ┃ * ┃ ┃ * ┃ ┻ ┃ * ┃ ┃ * ┗━┓ ┏━┛ * ┃ ┃神獸保佑 * ┃ ┃代碼無(wú)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執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】 * --------------------------------- * @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分頁(yè)插件 * --------------------------------- * @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 已經(jīng)自動(dòng)加載的資源。不手動(dòng)指定 * 配置文件和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 全局配置,更多內(nèi)容進(jìn)入類看注釋 GlobalConfiguration globalConfig = new GlobalConfiguration(); globalConfig.setDbType(DBType.MYSQL.name()); // ID 策略 AUTO->`0`("數(shù)據(jù)庫(kù)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; } /** * 注冊(cè)一個(gè)StatViewServlet * @return */ @Bean public ServletRegistrationBean DruidStatViewServle(){ //org.springframework.boot.context.embedded.ServletRegistrationBean提供類的進(jìn)行注冊(cè). ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); //添加初始化參數(shù):initParams //白名單: // servletRegistrationBean.addInitParameter("allow","127.0.0.1"); //IP黑名單 (存在共同時(shí),deny優(yōu)先于allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page. // servletRegistrationBean.addInitParameter("deny","192.168.1.73"); //登錄查看信息的賬號(hào)密碼. servletRegistrationBean.addInitParameter("loginUsername","root"); servletRegistrationBean.addInitParameter("loginPassword","root"); //是否能夠重置數(shù)據(jù). servletRegistrationBean.addInitParameter("resetEnable","false"); return servletRegistrationBean; } /** * 注冊(cè)一個(gè):filterRegistrationBean * * @return */ @Bean public FilterRegistrationBean druidStatFilter(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); //添加過(guò)濾規(guī)則. filterRegistrationBean.addUrlPatterns("/*"); //添加不需要忽略的格式信息. filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } }
這里是完整的配置文件,需要注意的是引入的包,別引錯(cuò)了!
4、還要開(kāi)啟dao的掃描,很簡(jiǎn)單,就是在啟動(dòng)文件中添加@MapperScan("com.tdx.account_service.dao*"),如下是完整的
到這里,配置算是完成了,運(yùn)行一下項(xiàng)目是可以運(yùn)行起來(lái)的。
我覺(jué)得Mybatis-Plus最好玩得應(yīng)該是代碼生成器這部分內(nèi)容,下面是代碼生成器的使用過(guò)程
pom.xml上要加點(diǎn)東西
<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 * ┏┓ ┏┓ *┏┛┻━━━┛┻┓ *┃ ┃ *┃ ━ ┃ *┃ ┳┛ ┗┳ ┃ *┃ ┃ *┃ ┻ ┃ *┃ ┃ *┗━┓ ┏━┛ * ┃ ┃神獸保佑 * ┃ ┃代碼無(wú)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)// 開(kāi)啟 activeRecord 模式 .setEnableCache(false)// XML 二級(jí)緩存 .setBaseResultMap(true)// XML ResultMap .setBaseColumnList(true)// XML columList .setOpen(false)//生成后打開(kāi)文件夾 .setAuthor(authorName) // 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性! .setMapperName("%sMapper") .setXmlName("%sMapper") .setServiceName("%sService") .setServiceImplName("%sServiceImpl") .setControllerName("%sController") ).setDataSource( // 數(shù)據(jù)源配置 new DataSourceConfig() .setDbType(DbType.MYSQL)// 數(shù)據(jù)庫(kù)類型 .setTypeConvert(new MySqlTypeConvert() { // 自定義數(shù)據(jù)庫(kù)表字段類型轉(zhuǎn)換【可選】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("轉(zhuǎn)換類型:" + 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)// 全局大寫(xiě)命名 //.setDbColumnUnderline(true)//全局下劃線命名 .setTablePrefix(new String[]{prefix})// 此處可以修改為您的表前綴 .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略 .setInclude(new String[] { table }) // 需要生成的表 .setRestControllerStyle(true) //.setExclude(new String[]{"test"}) // 排除生成的表 // 自定義實(shí)體父類 // .setSuperEntityClass("com.baomidou.demo.TestEntity") // 自定義實(shí)體,公共字段 //.setSuperEntityColumns(new String[]{"test_id"}) .setTableFillList(tableFillList) // 自定義 mapper 父類 // .setSuperMapperClass("com.baomidou.demo.TestMapper") // 自定義 service 父類 // .setSuperServiceClass("com.baomidou.demo.TestService") // 自定義 service 實(shí)現(xiàn)類父類 // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl") // 自定義 controller 父類 .setSuperControllerClass("com.tdx."+packageName+".controller.AbstractController") // 【實(shí)體】是否生成字段常量(默認(rèn) false) // public static final String ID = "test_id"; // .setEntityColumnConstant(true) // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false) // public User setName(String name) {this.name = name; return this;} // .setEntityBuilderModel(true) // 【實(shí)體】是否為lombok模型(默認(rèn) false)<a 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")// 這里是控制器包名,默認(rèn) web .setEntity("entity") .setMapper("dao") .setService("service") .setServiceImpl("service.impl") //.setXml("mapper") ).setCfg( // 注入自定義配置,可以在 VM 中使用 cfg.abc 設(shè)置的值 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( // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄 new TemplateConfig().setXml(null) // 自定義模板配置,模板可以參考源碼 /mybatis-plus/src/main/resources/template 使用 copy // 至您項(xiàng)目 src/main/resources/template 目錄下,模板名稱也可自定義如下配置: // .setController("..."); // .setEntity("..."); // .setMapper("..."); // .setXml("..."); // .setService("..."); // .setServiceImpl("..."); ); // 執(zhí)行生成 mpg.execute(); // 打印注入設(shè)置,這里演示模板里面怎么獲取注入內(nèi)容【可無(wú)】 System.err.println(mpg.getCfg().getMap().get("abc")); } }
文件中修改的內(nèi)容還是很多的,最主要的還是mysql的連接信息,沒(méi)理由你賬號(hào),密碼都錯(cuò)了還能連得上吧,其次設(shè)置一下你生成的模板文件路徑,我這里生成的路徑在上面圖可以看得到,是在com.tdx.account_service下的,注意,xml文件要放在resources下,不然是識(shí)別的,說(shuō)找不到這個(gè)方法
按照官網(wǎng)的代碼模板生成的文件基本是白白的,主要是mybatis-Plus集成了公共方法,很多常用的工具都可以引用了。在這里我提供一下我修改后Controller.java.vm文件,主要還是按照我自己的習(xí)慣去弄的
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 * ┏┓ ┏┓ *┏┛┻━━━┛┻┓ *┃ ┃ *┃ ━ ┃ *┃ ┳┛ ┗┳ ┃ *┃ ┃ *┃ ┻ ┃ *┃ ┃ *┗━┓ ┏━┛ * ┃ ┃神獸保佑 * ┃ ┃代碼無(wú)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 : 獲取分頁(yè)列表 * --------------------------------- * @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 : 通過(guò)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 : 通過(guò)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 : 通過(guò)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; } }
除了這個(gè)文件,其他代碼模板我都是按照官網(wǎng)那樣的,這里引用3個(gè)外部的文件,有AbstractController.java(控制器基類)、DatatablesJSON.java和JSONResult.java,然后這些文件又引用了其他文件,我懵逼了,怎么文件這么多啊,看來(lái)如果全部都貼上來(lái)得多占地方啊,所以我選擇相信碼云,如果需要請(qǐng)?jiān)诖a云上按照少的文件下載,碼云地址。需要注意的是,我的模板是直接代替了mybatis-plus.jar中的templates目錄。
最后就到了測(cè)試過(guò)程
下面的代碼段都是放在Controller文件里面,然后啟動(dòng)程序,對(duì)應(yīng)端口,請(qǐng)求方法。測(cè)試的話是需要按照自己的實(shí)體類操作的,所以僅供參考。
/** * 分頁(yè) PAGE */ @GetMapping("/test") public Page<User> test() { return userService.selectPage(new Page<User>(0, 12)); } /** * AR 部分測(cè)試 */ @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("查詢插入結(jié)果:" + 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("刪除一條數(shù)據(jù):" + userService.deleteById(1L)); System.err.println("插入一條數(shù)據(jù):" + 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); // 自動(dòng)回寫(xiě)的ID Long id = user.getId(); System.err.println("插入一條數(shù)據(jù):" + 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、分頁(yè) size 一頁(yè)顯示數(shù)量 current 當(dāng)前頁(yè)碼 * 方式一:http://localhost:8080/user/page?size=1¤t=1<br> * 方式二:http://localhost:8080/user/pagehelper?size=1¤t=1<br> */ // 參數(shù)模式分頁(yè) @GetMapping("/page") public Object page(Page page) { return userService.selectPage(page); } // ThreadLocal 模式分頁(yè) @GetMapping("/pagehelper") public Object pagehelper(Page page) { PageHelper.setPagination(page); page.setRecords(userService.selectList(null)); page.setTotal(PageHelper.freeTotal());//獲取總數(shù)并釋放資源 也可以 PageHelper.getTotal() return page; } /** * 測(cè)試事物 * http://localhost:8080/user/test_transactional<br> * 訪問(wèn)如下并未發(fā)現(xiàn)插入數(shù)據(jù)說(shuō)明事物可靠??!<br> * http://localhost:8080/user/test<br> * <br> * 啟動(dòng) Application 加上 @EnableTransactionManagement 注解其實(shí)可無(wú)默認(rèn)貌似就開(kāi)啟了<br> * 需要事物的方法加上 @Transactional 必須的哦??! */ @Transactional @GetMapping("/test_transactional") public void testTransactional() { //userService.insert(new User(1000L, "測(cè)試事物", 16, 3)); System.out.println(" 這里手動(dòng)拋出異常,自動(dòng)回滾數(shù)據(jù)"); throw new RuntimeException(); }
這么多的測(cè)試,我覺(jué)得最有趣的是條件構(gòu)造器,在官網(wǎng)上有更齊全的,而我這里是按照我自己的需求寫(xiě)的。
最后謝謝大家的觀看,寫(xiě)博客經(jīng)驗(yàn)不足,寫(xiě)得不好請(qǐng)見(jiàn)諒,如果能給你帶來(lái)幫助請(qǐng)點(diǎn)個(gè)贊,若遇到不明白的,或者我有寫(xiě)錯(cuò)的地方請(qǐng)?zhí)岢?,謝謝!也希望大家多多支持創(chuàng)新互聯(lián)。
網(wǎng)站名稱:springboot整合mybatis+mybatis-plus的示例代碼
標(biāo)題鏈接:http://www.rwnh.cn/article14/jeeede.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營(yíng)銷推廣、網(wǎng)站改版、移動(dòng)網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作、云服務(wù)器、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)