Spring Boot - это новая вещь для меня. Во время учебного процесса я обнаружил, что эта вещь все еще легко начать. Когда Spring Boot не будет настроен, он будет использовать Spring Data JPA по умолчанию. Это можно сказать, что это очень простой инструмент, но я все еще предпочитаю использовать Mybatis. Нет лучшего инструмента, только этот подходит для меня.
Говоря о Mybatis, в последнее время есть очень полезный инструмент - Mybatis -Plus (официальный сайт). Обновленная версия теперь 2,1.2, и эта версия также используется здесь. Мои любимые функции - это генераторы кодов и условные конструкторы, чтобы их можно было легче разрабатывать.
На официальном сайте Mybatisplus есть пример Spring Boot. Я последовал за этим, и программа не работала. Позже я узнал, что база данных H2, используемая DEMO, не то же самое, что MySQL. Поэтому, если вы хотите интегрировать mybatisplus, вы не можете смотреть на официальный веб -сайт и избегать обхода.
Ниже приведен процесс интеграции
1. Во -первых, вам нужно получить все необходимые файлы JAR. То, что вам нужно для pom.xml, следующие
pom.xml (неполный)
<!-mybatis-plus begin-> <dependency> <groupid> com.baomidou </GroupId> <ArtifactId> mybatisplus-spring-boot-starter </artifactid> <sersive> 1.0.4 </ression> </redybatipis-plus> <groupid> com.baomidou <version>2.1.2</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- mybatis-plus end --><!-- druid Alibaba database connection pool--><dependency> <groupId>com.alibaba</groupId> <TrifactId> Druid </artifactid> <sersion> 1.1.3 </version> </dependency> <!-MySQL-> <Depected> <groupid> mySQL </GroupId> <artifactid> mysql-connector-java </artifactid> <cract> runtime </scope> </зависимость> <зависимость> java> </runtime </scope> </reperty> <зависимость> <Degy> <groupId> org.mybatis.spring.boot </GroupId> <artifactid> mybatis-spring-boot-starter </artifactid> <sersion> 1.3.1 </version> </depertive>
2. Добавьте конфигурации, связанные с mybatis, такие как учетная запись, пароль и т. Д. Здесь я использовал Application.yml для соответствия.
Application.yml
Сервер: Порт: 8080#SpringsPring: DevTools: перезапуск: включено: true#Это для горячего развертывания, и это не связано с MyBatis#Database DataSource: Driver-Class-Name: com.mysql.jdbc.driver username: root пароль: root url: root: root: root url: com.mysql.jdbc.driver. jdbc: mysql: // mysqldb: 3306/tdx_shop? useUnicode = true & hareverencoding = utf-8 Тип: com.alibaba.druid.pool.druiddatasource #Here настраивает пул соединений Druid. Ниже приведены вся информация о конфигурации для фильтров друида: статистика, стена, log4j maxactive: 20 инициализируется: 1 макс. maxopenpreparedStatements: 20-пропертистики соединения: druid.stat.merggsql = ture; druid.stat.slowsqlmillis = 5000 #mybatismybatis: mapper-locations: classpath*:/mapper/** mapper.xml #cult xml-файл в com.xx.mapper. Вот Mapper в соответствии с ресурсом #Eentity, несколько пакетов разделены запятыми или полуколонами. Typealiasespackage: com.tdx.account_service.entity #Это местоположение конфигурации класса объекта: Map-underscore-to-camel-case: True Cache-Sabled: false #loggingLogging: Уровень: Warn
Вещи конфигурации аналогичны тому, что мы использовали для настройки с помощью Mybatis, но Spring Boot не имеет файла конфигурации XML. Обратите внимание на содержание красной буквы, в основном нет проблем.
3. Файл конфигурации mybatis-plus ------ mybatisplusconfig. Во -первых, давайте объясним путь файла на рисунке выше. Среди них mybatisplusconfig помещается в папку конфигурации, в то время как файл XML помещается в Mapper в соответствии с повторными.
Тогда есть часть контента mybatisplusconfig
Mybatisproperties.java
пакет com.tdx.account_service.config; import com.alibaba.druid.pool.druiddatasource; import com.alibaba.druid.support.http.statviewservlet; importibaba.druid.support.http.webstatfilter; com.baomidou.mybatisplus.mybatisconfiguration; импорт com.baomidou.mybatisplus.mybatisconfiguration; импорт com.baomidou.mybatisplus.entity.globalconfiguration; импорт com.baomidou.mybatisplus.enums.dbtype; com.baomidou.mybatisplus.plugins.paginationInterceptor; импорт com.baomidou.mybatisplus.plugins.performanceInterceptor; импорт com.baomidou.mybatisplus.plugins.parser.isqlparser; import com.baomidou.mybatisplus.plugins.parserser; import com.baomidou.mybatisplus.pluginser. com.baomidou.mybatisplus.plugins.parser.tenant.tenanthandler; импорт com.baomidou.mybatisplus.plugins.parser.tenant.tenantsqlparser; импорт com.baomidou.mybatisplus.spring.mybatissqlsessionFactorybean; com.baomidou.mybatisplus.spring.boot.starter.springbootvfs; импорт com.baomidou.mybatisplus.toolkit.pluginutils; импорт net.sf.jsqlparser.expression.expression; импорт net.sf.jsqlpary.expression.longvale. org.apache.ibatis.mapping.databaseidprovider; import org.apache.ibatis.mapping.mappedstatement; import org.apache.ibatis.plugin.interceptor; импорт org.apache.ibatis.reflection.metaobject; импорт org.mybatis.spring.annotation.mapperscan; org.mybatis.spring.boot.autoconfigure.mybatisproperties; импорт org.springframework.beans.factory.annotation.autowired; импорт org.springframework.boot.bindtory.relaxedpropertyresolver; импорт org.springframework.boot.context.properties.enableConfigurationProperties; импорт org.springframework.boot.web.servlet.filterRegistrationbean; импорт org.springframework.boot.web.servlet.servletregistrationbeanbeanbeanbeanbeanbeanbeanbenbeanbe. org.springframework.context.annotation.configuration; import org.springframework.core.env.environment; импорт org.springframework.core.io.defaultresourceloader; импорт org.springframework.core.io.resourceler; org.springframework.util.stringutils; импорт javax.sql.datasource; импорт java.sql.sqlexception; импорт java.util.arraylist; import java.util.list;/** * Код находится далеко от ошибки, защищающего животное * ┏┓ ┏┛━━━━━┛┻┓ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ * * ┗┳ ┃ * ┃ ┃ * ┃ ┃ * ┃ ┗┳ ┃ * ┃ ┃ * ┃ ┏━┛ ┏━┛ * ┃ ┃ ┃ Благословение зверя * ┃ ┃ ┃ ┃ ┃ ┗┓ ┏┛ * ┃ ┃ ┃ Благослови зверя * ┃ ┃ ┃ ┃ ┃ ┃ ┏┛ ┃ ┃ * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * @description: mybatisplus configuration * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Частный RELECEDPROPERTYRESOLVER PropertyResolver; @Autowired Private DataSource DataSource; @Autowired частные свойства mybatisproperties; @Autowired Private ResourceLoader ResourceLoader = новый DefaulTresourceloAder (); @Autowired (требуется = false) частный перехватчик [] перехватчики; @Autowired (required = false) частная база данных базы данных; /** * @Description: MyBatis-Plus SQL Effication Plug-модернизация [может быть закрыт в производственной среде] * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ @Bean public DataSource druiddatasource () Throws sqlexception {this.propertyresolver = new RelexedPropertyResolver (среда », Spring.datasource.»); System.out.println ("================================================================================== ============================================================================================================= ======================================================================================================== ============================================================================================================= DataSource.Seturl (PropertyResolver.getProperty («URL»); dataSource.SetInitialSize (integer.valueof (PropertyResolver.getProperty («Начальный размер»)); dataSource.setMaxWait (long.valueof (PropertyResolver.getProperty ("max-wait"))); DataSource.SetmineVictableIdletImemillis (long.valueof (PropertyResolver.getProperty ("Min-Evictable-Idle-Millis")); /** * @Description : mybatis-plus pagination plugin* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- : Create В 2017/9/19 13:59*/@Bean Public PaginationInterceptor PaginationInterceptor () {PaginationInterceptor Page = New PaginationInterceptor (); *@Bean public mybatissqlsessionfactorybean mybatissqlSessionFactorybean () {mybatissqlSessionFactorybean mybatisplus = new MybatissqlSessionFactoryBean (); (StringUtils.hastext (this.properties.getConfiglocation ())) {mybatisplus.setConfiglocation (this.resourceloader.getresource (this.properties.getConfiglocation ()); (! Objectutils.isempty (this.interceptors) {mybatisplus.setplugins (this.interceptors); ID Self-Increment ") Input->` 1` (идентификатор пользователя ") ID_WORKER->` 2` ("Глобальный уникальный идентификатор") UUID-> `3` (" Global Unique ID ") GlobalConfig.Setidtype (2); MC.SetDefaultscriptingLanguage (mybatisxmllangugeardriver.class); (StringUtils.haslength (this.properties.getTypealiasSpackage ()))) {mybatisplus.settypealiasSpackage (this.properties.getTypealiasSpackage ()); } if (stringUtils.haslength (this.properties.gettypealiasespackage ());} if (stringutils.haslength (this.properties.gettypehandlerspackage ())) {mybatisplus.settypehandlerspackage (это. (! Objectutils.isempty (this.properties.resolvemapperlocations ())) {mybatisplus.setmapperlocations (this.properties.resolvemapperlocations ()); DruidStatviewServle () {//org.springframework.boot.context.embedded.servletregistrationbean обеспечивает класс для регистрации. ServletRegistrationBean.AddinitParameter ("Alling", "127.0.0.1"); Пароль для просмотра. Один из них: FilterRegistrationBean * * @return */@bean Public FilterRegistrationbeanbeanbeanbeanbelter () {FilterRegistrationBean FileChistragebean = New FilterRegistrationBean (New WebStatfilter ()); игнорируется.Вот полный файл конфигурации. Важно отметить, что введенные пакеты не являются неправильными!
4. Вам также нужно включить сканирование DAO. Это очень просто. Добавить @mapperscan ("com.tdx.account_service.dao*") в файл запуска. Ниже приведено полное.
На этом этапе конфигурация была завершена, и вы можете запустить проект после его запуска.
Я думаю, что Mybatis-Plus-самая забавная часть генератора кода. Ниже приведен процесс использования генератора кода
Добавить что -нибудь в pom.xml
<depervice> <groupid> org.apache.velocity </GroupId> <artifactId> Velocity-engine-core </artifactid> <sersive> 2.0 </version> </depervice>
1. Файл конфигурации генератора кода
Mybatisplusconfig.java
/*** Copyright (C) 2011-2016, Hubin ([email protected]). * <p> * Лицензирован по лицензии Apache, версия 2.0 («Лицензия»); Вы не можете * использовать этот файл, кроме как в соответствии с лицензией. Вы можете получить копию * Лицензии в * <p> * http://www.apache.org/license/license-2.0 * <p> *, если не требуется применимый закон или не согласен в письменной форме, программное обеспечение * распределяется в соответствии с лицензией, распределяется на «как это», без * гарантий или условий каких-либо видов, либо экспрессированного, либо на лицензии. См. * Лицензию для конкретного языка, регулирующих разрешения и ограничения в соответствии с * лицензией. */package com.tdx.account_service.generator; import java.io.file; импорт java.util.arraylist; import java.util.collections; импорт java.util.hashmap; import java.util.list; импорт java.util.map; import com.baomidou.mybatisplus. com.baomidou.mybatisplus.generator.autogenerator; import com.baomidou.mybatisplus.generator.incectonfig; импорт com.baomidou.mybatisplus.generator.config.datasourceconfig; import com.baomidou.mybatisplus.generator.config.com com.baomidou.mybatisplus.generator.config.globalconfig; import com.baomidou.mybatisplus.generator.config.packageconfig; импорт com.baomidou.mybatisplus.generator.config.strategyconfig; импорт com.baomidou.mybatisplus.generator.config.templateconfig; import com.baomidou.mybatisplus.generator.config.converts.mysqltypeconvert; import com.baomidou.mybatisplus.generator.config.po.tablefill; com.baomidou.mybatisplus.generator.config.po.tableinfo; импорт com.baomidou.mybatisplus.generator.config.rules.dbcolumntype; импорт com.baomidou.mybatisplus.generator.config.rules.dbtype; com.baomidou.mybatisplus.generator.config.rules.namingStrategy;/** *Код далеко от ошибки с защитой животного *┏┓ *┏┛━━━━━━━┛┻┓ *┃ ┃ *━ ┃ * БУГЫ! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * @description: Mybatisplus Code Generator * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Путь файла частная статическая строка Authorname = "liang.guangqing"; // автор частной статической строки таблицы = "sc_user"; // имя таблицы частная статическая строка префикс = "sc_"; // Префикс таблицы Private Static File File = New File (packageName); private static String path = file.getAbsolutePath (); public static void main (string [] args) {// Настроить поля, которые необходимо заполнить список <tableFill> TableFillList = new ArrayList <> (); TableFillList.Add (New TableFill ("asdd_ss", fieldfill.insert_update)); // Code Generator AutoGenerator mpg = new AutoGenerator().setGlobalConfig( // Global configuration new GlobalConfig() .setOutputDir(path+"/src/main/java")// Output directory.setFileOverride(true)// Whether to overwrite the file.setActiveRecord(true)// Enable activeRecord mode.setEnableCache(false)// XML Вторичный cache.setbaseresultmap (true) // xml resultmap .setbasecolumnlist (true) // xml -списк. .setxmlname ("%smapper") .setserviceName ("%sservice") .setServiceImplname ("%sserviceimpl") .setControllernam type.settypeconvert (new mysqltypeconvert () {// Настройка поля таблицы баз данных тип типа [необязательно] @override public dbcolumntype processtypeconvert (String fieldtype) {System.out.println ("Confurtion Type:" + FieldType); // if (fieldype.toLAORCASE (). // return dbcolumntype.boolean; .seturl ("JDBC: MySQL: //127.0.0.1: 3306/tdx_shop? Harmentencoding = utf8")) .setStrategy (// Конфигурация политики New StrategyConfig () // .setcaletmode (true) // naming //setdbullunduldline number naming.settableprefix (new String [] {prefix}) // Здесь вы можете изменить его на префикс своей таблицы .setnamil String [] {"test"}) // исключить сгенерированную таблицу // пользовательский объект родительского класса // .setSuperentityClass ("com.baomidou.demo.testentity") // Custom Entity, public Field //setsuperentitycolumns(new string [] {"test_id"}) .setablefillfill (tablefill listslist). .setsupermapperclass ("com.baomidou.demo.testmapper") // пользовательская служба родительской класс // .setsuperserviceclass ("com.baomidou.demo.testservice") // Индивидуальная реализация обслуживания. .setsuperControllerclass ("com.tdx."+PackageName+". Controller.abstractController") // [Entity] Снижение константы поля (false) // public static final String id " {this.name = name; // .setentitybooleAncolumnRemoveIspRefix (true) // .setRestControllerStyle (true) // .setControllermappingHyphenStyle (true)) .setPackageInfo (// packageConfig () // .setModulEaname («пользователь».). path.setController("controller")// Here is the controller package name, default web .setEntity("entity") .setMapper("dao") .setService("service") .setServiceImpl("service.impl") //.setXml("mapper") ).setCfg( // Inject custom configuration, you can use the value set by cfg.abc in VM new InceptionConfig () {@override public void initmap () {map <string, object> map = new Hashmap <> (); } .setFileOutConfigList (Collections. <FieleOutConfig> singletonList (new FileOutConfig ("/templates/mapper.xml.vm") {// Пользовательский каталог выходных файлов @override public Stringfile (tableInfo tableInfo) {return Path + "/src/main/resources/" + tableInfo) "Mapper.xml"; SRC/Ресурсы/Шаблон. .setServiceImpl ("..."); // Выполнить для генерации mpg.execute (); // Печать настройки впрыска, здесь продемонстрируйте, как получить содержание впрыска в шаблоне [Noble] System.err.println (mpg.getcfg (). Getmap (). Get ("abc")); }}
В файле все еще есть много изменений. Самое главное - информация о соединении MySQL. Нет причин, по которым ваша учетная запись и пароль неверны. Вы можете подключиться к этому. Во -вторых, установите путь сгенерированного вами файла шаблона. Путь, который я сгенерировал здесь, можно увидеть на рисунке выше. Он находится под com.tdx.account_service. Обратите внимание, что файл XML должен быть размещен в ресурсах, в противном случае он будет признан и сказал, что этот метод не может быть найден.
Файлы, сгенерированные в соответствии с шаблоном кода официального веб -сайта, в основном пусты. Основная причина заключается в том, что Mybatis-Plus интегрирует общественные методы, и можно ссылаться на многие часто используемые инструменты. Здесь я предоставляю файл Controller.java.vm, который я изменил, в основном в соответствии с моими собственными привычками.
Controller.java.vm
Пакет $ {package.controller}; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestparam; #if ($ {restControllersTyle}) импорт org.spramework.web.bindtation.Requed.Requod.RequeD. org.springframework.web.bind.annotation.RestController;#elseimport org.springframework.steretype.Controller;#end#if(${superControllerClassPackage})import ${superControllerClassPackage};#endimport 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.altity}. $ {package.entity}. $ {entity}; import org.slf4j.logger; import org.slf4j.loggerfactory;/** *Код находится далеко от ошибки с защитой животного *┏┓ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ *┃ ┗┓ ┏━┛ *┃ ┃ *┃ ┃ *┗┓ ┏━┛ *┃ ┃ ┃ *┃ ┃ *┗┓ ┏━┛ *┃ ┃ ┃ Благословение *┃ ┃ Код не имеет ошибок! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫┃┫ * ┗┻┛ ┗┻┛ * * @description: $ {entity} Контроллер * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------. */#if ($ {restControllerStyle})@restcontroller#else@controller#end@requestmapping ("#if ($ {package.modulename})/$ {package.modulename}# end/#if ($ {controlermappingHyphenStyle}) $ {controlermAppingHyphen}#else $ {table.entityPath} #end ")#if ($ {superControllerClass}) публично Class $ {table.controllername} extends $ {supercontrollerclass} {#elsepublic class $ {table.controllername} {! @Autowired public $ {table.serviceName} $ {table.entityPath} Service; /*** @Description: Получить список подкидки* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- RequestMethod.POST) public Object Получить $ {entity} list ($ {entity} param, @requestparam (value = "draw", defaultvalue = "0") integer draw, @requestparam (value = "length") integer длина, @requestparam (value = "start") integer start) {datatablesjson <$ {entity}> resjson = resjson = resjson = resjson = resjson = newaTables <$ {entity}> resjson = neaTablables. try {integer pageno = getPageno (start, длина); Page <$ {entity}> 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: получить $ {entity} от id * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 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: Delete $ {entity} от id * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 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 : Update ${entity} by id * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- @since : Create in $ {date} */ @Requestmapping (value = "/ uppleation $ {entity} byid", method = requestMethod.post) Обновление общедоступного объекта $ {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} * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 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. Затем эти файлы относятся к другим файлам. Я был в замешательстве. Почему так много файлов? Кажется, что если все они будут размещены, это займет больше места. Поэтому я решил верить в облако кода. Если вам это нужно, пожалуйста, загрузите облако кода в соответствии с несколькими файлами в Code Cloud. Следует отметить, что мои шаблоны напрямую заменяются каталогом шаблонов в mybatis-plus.jar.
Наконец, это процесс тестирования
Следующие фрагменты кода помещаются в файл контроллера, а затем запускается программа, соответствующая порту и методу запроса. Для тестирования вам необходимо работать в соответствии со своим собственным классом организации, так что это только для справки.
/** * Страница страниц */@getmapping ("/test") public page <user> test () {return userservice.selectpage (новая страница <user> (0, 12)); }/*** AR Partial Test*/@GetMaping ("/test1") Общественная страница <user> test1 () {user user = new user (); System.err.println ("Delete All:" + 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("Query insert result: " + user.selectById().toString()); //user.setNickname("mybatis-plus-ar"); System.err.println("Update:" + user.updateById()); return user.selectPage(new Page<User>(0, 12), null); } /** * Add, delete, modify and check 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("Delete a data: " + userService.deleteById(1L)); System.err.println("Insert a data: " + 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); // Automatic writeback ID Long id = user.getId(); System.err.println("Insert a piece of data: " + result + ", Insert information: " + user.toString()); System.err.println("Query: " + 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()); результат возврата; } /** * 7. Pagination size Number of displays on one page Current page number* Method 1: http://localhost:8080/user/page?size=1¤t=1<br> * Method 2: http://localhost:8080/user/pagehelper?size=1¤t=1<br> * / // Parameter mode pagination @GetMapping("/page") public Object page(Page page) { return userService.selectPage(page); } // ThreadLocal Pattern pagination @GetMapping("/pagehelper") public Object pagehelper(Page page) { PageHelper.setPagination(page); page.setRecords(userService.selectList(null)); page.setTotal(PageHelper.freeTotal());//Get the total number and free resources. PageHelper.getTotal() return page; } /** * Test things* http://localhost:8080/user/test_transactional<br> * Access the following and no data is found to indicate that things are reliable! ! <br> * http://localhost:8080/user/test<br> * <br> * Start Application Add @EnableTransactionManagement The annotation seems to be enabled without default<br> * Methods that require things plus @Transactional is a must! ! */ @Transactional @GetMapping("/test_transactional") public void testTransactional() { //userService.insert(new User(1000L, "Test Things", 16, 3)); System.out.println("Exception is thrown manually here and data is automatically rolled back"); throw new RuntimeException(); }这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。
最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!也希望大家多多支持武林网。