Boot Spring هو شيء جديد بالنسبة لي. خلال عملية التعلم الخاصة بي ، وجدت أن هذا الشيء لا يزال من السهل البدء. عند عدم تكوين Boot SPRING ، فإنه سيستخدم بيانات SPRING DATA JPA افتراضيًا. يمكن قول هذا الشيء ليكون أداة بسيطة للغاية ، لكنني ما زلت أفضل استخدام MyBatis. لا توجد أفضل أداة ، فقط هذه الأداة مناسبة لي.
عند الحديث عن MyBatis ، هناك أداة مفيدة للغاية مؤخرًا - MyBatis -Plus (موقع رسمي). الإصدار المحدث هو الآن 2.1.2 ، ويستخدم هذا الإصدار أيضًا هنا. الميزات المفضلة لدي هي مولدات الرموز والمنشآت الشرطية ، بحيث يمكن تطويرها بسهولة أكبر.
يوجد مثال على حذاء الربيع على الموقع الرسمي لـ MyBatisPlus. تابعت ذلك ولم يركض البرنامج. في وقت لاحق اكتشفت أن قاعدة بيانات H2 المستخدمة من قبل العرض ليست هي نفسها MySQL. لذلك إذا كنت ترغب في دمج MyBatisPlus ، فيمكنك النظر إلى الموقع الرسمي وتجنب التفاف.
فيما يلي عملية التكامل
1. أولاً ، تحتاج إلى الحصول على جميع ملفات جرة المطلوبة. الأشياء التي تحتاجها لـ pom.xml هي كما يلي
pom.xml (غير مكتمل)
<!-mybatis-plus begin-> <redency> <roupiD> com.baomidou </rougeid> <StifactId> mybatisplus-spring-boot-starter </tenfactid> <sperive> 1.0.4 </sperence> </sperency> <sependency> com.baomidou> <sperive> 2.1.2 </splese> </sependency> <redency> <roupiD> org.springframework.boot </rougeid> <StifactId> spring-boot-starter-jdbc </tefactid> </reperence> <!-mybatis-plus end-> <! <roughId> com.alibaba </rougiD> <StifactId> druid </stifactId> <الإصدار> 1.1.3 </الإصدار> </repreadency> <!-mysql-> <redence> <roupid> mysql </rougiD> <terfactid> mysql-connect <roupl> org.mybatis.spring.boot </rougeid> <StifactId> mybatis-spring-boot-starter </shintifactid> <splection> 1.3.1 </soph> </redenced>
2. أضف التكوينات المتعلقة بـ MyBatis ، مثل الحساب وكلمة المرور ، إلخ. هنا استخدمت Application.yml للمطابقة.
application.yml
الخادم: المنفذ: 8080#SpringSpring: DevTools: إعادة التشغيل: ممكّن: True#هذا للنشر الساخن ، ولا يرتبط بـ MyBatis#Database Config Configurce: اسم برنامج التشغيل -سائق: com.mysql.jdbc.driver username: Root Password: Root Url: JDBC: mysql: // mysqldb: 3306/tdx_shop؟ useUnicode = true & directionoding = utf-8 type: com.alibaba.druid.pool.druiddataSource #here yere reaviant the druid connection. فيما يلي جميع معلومات التكوين لمرشحات Druid: STAT ، WALD ، LOG4J MAXACAITY: 20 التهيئة: 1 MAXWAIT: 60000 MINIDLE: 1 TTIMETWENEVICTIONRUNSMILLIS MaxOpenPreparedStatements: 20 اتصالات الاتصال: druid.stat.merggsql = ture ؛ druid.stat.slowsqlmillis = 5000 #mybatismybatis: mapper-locations: classpath*:/mapper/** mapper.xml فيما يلي Mapper ضمن المسح الضوئي للموارد ، يتم فصل حزم متعددة بواسطة فواصل أو فاصلة فاصلة. typealiasespackage: com.tdx.account_service.entity #هذا هو موقع تكوين فئة الكيان: map-underscore to-case: true cache-enbord: false #logginglogging: level: warn
تشبه أشياء التكوين ما استخدمناه لتكوينه باستخدام MyBatis ، لكن Boot Spring لا يحتوي على ملف تكوين XML. انتبه إلى محتوى الرسالة الحمراء ، لا توجد مشكلة في الأساس.
3. ملف تكوين MyBatis-Plus ------ MyBatisPlusConfig. أولاً ، دعنا نوضح مسار الملف في الشكل أعلاه. من بينها ، يتم وضع MyBatiSplusConfig في مجلد التكوين ، بينما يتم وضع ملف XML في Mapper تحت resouces.
ثم هناك جزء محتوى MyBatisPlusConfig
mybatisproperties.java
package com.tdx.account_service.config ؛ استيراد com.alibaba.druid.pool.druiddatasource ؛ استيراد com.alibaba.druid.support.http.statviewservlet ؛ استيراد com.alibaba.druid.support.http.webstatfilter ؛ com.baomidou.mybatisplus.mybatisconfiguration ؛ استيراد com.baomidou.mybatisplus.mybatisconfiguration ؛ استيراد com.baomidou.mybatisplus.entity.globalconfiguration ؛ استيراد com.baomidou.mybatpatplus.enums.dbtype. com.baomidou.mybatisplus.plugins.paginationInterceptor ؛ استيراد com.baomidou.mybatisplus.plugins.performanceInterceptor ؛ استيراد com.baomidou.mybatisplus.plugins.parser.isqlparser ؛ استيراد com.baomidou.mybatisplus.plugins.parser.isqlparserfilter ؛ استيراد com.baomidou.mybatisplus.plugins.parser.tenant.tenanthandler com.baomidou.mybatisplus.spring.mybatissqlsessionfactorybean ؛ استيراد com.baomidou.mybatisplus.spring.boot.starter.springbootvfs ؛ استيراد com.baomidou.mybatisplus.toolkit.pluginutils ؛ net.sf.jsqlparser.expression.expression ؛ استيراد net.sf.jsqlparser.expression.longvalue ؛ import org.apache.ibatis.mapping.databaseidprovider ؛ import org.apache.ibatis.mapping org.apache.ibatis.reflection.metaObject ؛ استيراد org.mybatis.spring.annotation.mapperscan ؛ استيراد org.mybatis.spring.boot.autoconfigure.mybatisproperties ؛ استيراد org.springframewew org.springframework.boot.bind.relaxedPropertyResolver ؛ استيراد org.springframework.boot.context.properties.enableConfigurationProperties ؛ استيراد org.springframework.boot.web.servlet.filterregistrationbean ؛ org.springframework.boot.web.servlet.servletregistrationbean ؛ استيراد org.springframework.context.annotation.bean ؛ استيراد org.springframework.context.annotation.configuration org.springframework.core.io.defaultresourceloader ؛ استيراد org.springframework.core.io.resourceloader java.sql.sqlexception ؛ import java.util.arraylist ؛ استيراد java.util.list ؛/** * بعيدا عن الخلل مع حماية الحيوان * ┏┓ ┏┓ * ┏┛━━━━━┛┻┓ * ┏┛━━━━━┛┻┓ * ┃ * ┃ * ┃ * ━ * ┃ * ┃ * ┃ * ┃ * ┳┛ * ┃ * ┃ * ┃ * ┃ * ┃ * ┃ ┃ يبارك من الوحش* ┃ ┃ ┃ ┃ ┃ ┗┓ ┗┓ ┏┛* ┃ ┃ ┃ يبارك من الوحش* ┃ ┃ ┃ ┃ ┃ ┃ no bugs! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * description: myBatisPlus configuration * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Private RelaxedPropertyResolver PropertyResolver ؛ Autowired الخاص بيانات البيانات البيانات الخاصة ؛ @autowired mybatisproperties خصائص ؛ @autowired private resourceLoader ResourceLoader = new defaultresourceloader () ؛ @autowired (مطلوب = خطأ) اعتراض خاص [] معترض ؛ Autowired (مطلوب = خطأ) databaseidprovider databaseidprovider databaseidprovider ؛ /** * Description: MyBatis-Plus SQL تنفيذ المكون الإضافي [يمكن إغلاقه في بيئة الإنتاج] * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ bean public dataSource DruidDataSource () يلقي sqlexception {this.propertyResolver = new RelaxedPropertyResolver (البيئة "spring.datasource.") ؛ System.out.println ("============================================================================================================================ =============================================================================================================================================== ================================================================================================================================================ =============================================================================================================================================== DataSource.Seturl (PropertyResolver.getProperty ("url") ؛ datasource.setinitialsize (integer.valueof (propertyResolver.getProperty ("size-size") ؛ datasource.setMaxactive (integer.valueof (propertyResolver.getProperty ("Max-Active")) ؛ DataSource.SetFilters (PropertyResolver.getProperty ("المرشحات") ؛ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- PAGINESTINGERINGENTINGERSINGEROPTOR (PAGINETING PAGETINGERES MyBatissqlSessioniTiveFactorybean MyBatissaTessionfactory () (stringutils.hastext (this.properties.getConfiglocation ()) {myBatisPlus.SetConfiglocation (this.resourceloader.getResource (this.properties.getConfiglocation ()) ؛ (! ObjectUtils.isempty (This.Noftors)) Auto-> `0` (" Database ID Self-Increment ") input->` 1` (معرف إدخال المستخدم ") id_worker->` 2` ("المعرف الفريد العالمي") uuid-> `3` (" المعرف الفريد العالمي ") mybatisconfiguration () ؛ (stringUtils.haslength (this.properties.gettypealiasespackage ())))) } if (stringUtils.hasLength (this.properties.gettypealiasespackage ()) ؛} if (stringUtils.hasLength (this.properties.gettypehandlerspackage ())) (! objectUls.isempty (this.properties.resolvemapperlocations ()) {mybatisplus.setMapperLocations (this.properties.resolvemapperlocations () ؛ DruidStatViewServle () {//org.springframework.boot.context.embedded.servletregistrationbean يوفر الفئة للتسجيل. // servletregistrationbean.addinitparameter ("السماح" ، "127.0.0.1") ؛ كلمة المرور لعرض المعلومات. * سجل: FilterRegistrationBean * */ @bean publicistrationbean druidstatfilter () تم تجاهله.هنا هو ملف التكوين الكامل. من المهم أن نلاحظ أن الحزم المقدمة ليست غير صحيحة!
4. تحتاج أيضًا إلى تمكين المسح الضوئي DAO. إنه بسيط للغاية. إضافة mapperscan ("com.tdx.account_service.dao*") إلى ملف بدء التشغيل. ما يلي هو واحد كامل.
في هذه المرحلة ، تم الانتهاء من التكوين ، ويمكنك تشغيل المشروع بعد تشغيله.
أعتقد أن MyBatis-Plus هو الجزء الأكثر متعة من مولد الرمز. فيما يلي عملية استخدام مولد الرمز
أضف شيئًا إلى pom.xml
<Rependency> <roupiD> org.apache.velocity </groupId> <StifactId> velocity-edgine-core </artifactid> <sophy> 2.0 </version> </sependency>
1. ملف تكوين مولد الرمز
MyBatisplusConfig.java
/*** حقوق الطبع والنشر (C) 2011-2016 ، Hubin ([email protected]). * <p> * مرخص بموجب ترخيص Apache ، الإصدار 2.0 ("الترخيص") ؛ لا يجوز لك * استخدام هذا الملف إلا في الامتثال للترخيص. يمكنك الحصول على نسخة من * الترخيص في * <p> * http://www.apache.org/licenses/license-2.0 * <p> * ما لم يكن مطلوبًا بموجب القانون المعمول به أو يتم الموافقة عليه في الكتابة ، يتم توزيع البرامج * الموزعة بموجب الترخيص على أساس "كما هو" ، بدون * ضمانات أو شروط من أي نوع ، إما التعبير أو الضمني. راجع ترخيص * لغوية محددة تحكم أذونات وقيود تحت * الترخيص. */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.baomido com.baomidou.mybatisplus.generator.autogenerator ؛ استيراد com.baomidou.mybatisplus.generator.injectionConfig ؛ استيراد com.baomidou.mybatisplus.generator.config.datasourconfig ؛ com.baomidou.mybatisplus.generator.config.globalconfig ؛ استيراد com.baomidou.mybatisplus.generator.config.packageconfig com.baomidou.mybatisplus.generator.config.templateconfig ؛ استيراد com.baomidou.mybatisplus.generator.config.converts.mysqltypeconvert ؛ استيراد com.baomidou.mybatisplus.generator.config.po.table com.baomidou.mybatisplus.generator.config.po.tableInfo ؛ استيراد com.baomidou.mybatisplus.generator.config.rules.dbcolumntype ؛ استيراد com.baomidou.mybatisplus.generator.config.dbtype ؛ com.baomidou.mybatisplus.generator.config.rules.namingstrategy ؛/** *الكود بعيدًا عن الخلل مع حماية الحيوان *┏┓ ┏┓ ┏┓ *┏┛━━━━━━━┛┻┓ *┃ *┃ *┃ ┃ ━ ┃ ┃ ┃ ┃ ┃ ┃ ┃ حشرات! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * description: myBatisplus Code Generator * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // path path private Static String AuthorName = "Liang.Guangqing" ؛ // المؤلف جدول السلسلة الثابتة = "SC_USER" ؛ // اسم الجدول بادئة السلسلة الثابتة = "sc_" ؛ // Premix Private File Static File File = ملف جديد (packagename) ؛ Private Static String Path = file.getabsolutepath () ؛ الفراغ الثابت العام (سلسلة [] args) {// تخصيص الحقول التي تحتاج إلى ملء قائمة <TableFill> tablefilllist = new ArrayList <> () ؛ TableFillList.add (Tablefill جديد ("ASDD_SS" ، fieldfill.insert_update)) ؛ // code generator autogenerator mpg = new Autogenerator (). cache.setbaseresultmap (صواب) // xml resultmap .SetBaseColumnList (true) // xml columnlist. .setxmlname ("٪ smapper") .SetServicename ("٪ sservice") .SetServiceImplName ("٪ sserviceimpl") .SetControllerName ("٪ scontroller"). type.settypeConvert (جديد mysqltypeconvert () {// تخصيص تحويل نوع حقل جدول قاعدة البيانات [اختياري] Override public dbcolumntype processTypeConvert (string fieldtype) {system.out.println ("نوع التحويل:" // return dbcolumntype.boolean ؛ .seturl ("jdbc: mysql: //127.0.0.1: 3306/tdx_shop؟ characterencoding = utf8") .SetStrategy (// تكوين السياسة الاستراتيجية الجديدة () //. naming.settableprefix (سلسلة جديدة [] {prefix}) // هنا يمكنك تعديلها إلى prefix.setnaming (namingstrategy.underline_to_camel) String [] {"test"}) // استبعاد الجدول الذي تم إنشاؤه // Custom Entity Parent Class // .setsuperentityclass ("com.baomidou.demo.testentity") .SetSuperMapperClass ("com.baomidou.demo.testmapper") Controller Parent Class .SetSuperControllerClass ("com.tdx."+packagename+". controller.abstractController") الاسم) {this.name = name ؛ Field // .SetentityBooleanColumnRemoveSprefix (true) //. path.setController ("Controller") // هنا اسم حزمة وحدة التحكم ، الويب الافتراضي. InjectionConfig () {Override public void () {map <string ، Object> map = new HashMap <> () ؛ }. "mapper.xml" ؛ SRC/Main Resources Comply. .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 $ {package.controller} ؛ استيراد org.springframework.web.bind.annotation.requestmapping ؛ استيراد org.springframework.web.bind.annotation.requestparam ؛ org.springframework.web.bind.annotation.restController ؛ #elseimport org.springframework.steretety.controller ؛#end#if ($ {superControllerClassPackage}) استيراد $ {supercontrollerClassPackageage} ؛#endimport org.springframework.beans.factory.annotation. $ {package.entity} .Common.DatatablesJson ؛ import $ {package.entity} .Common.jsonresult ؛ import $ {package.entity}. $ {entity} ┃ *┃ ┳┛ ┗┳ ┃ *┃ ┃ *┃ ┃ *┃ ┃ ┗┳ ┃ *┃ ┃ *┃ ┃ ┃ *┃ ┃ *┃ ┗┓ ┏━┛ *┃ ┃ *┃ ┃ *┃ ┗┓ ┗┓ *┃ ┃ ┃ *┃ ┃ ┃ ┗┓ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗┓ ┃ ┃ ┃ ┃ ┃ ┃ *┗┓ ┗┓ ┗┓ ┃ ┃ ┃ * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫┃┫ * ┗┻┛ ┗┻┛ * * description: $ {entity} controller * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */#if ($ {restControllersTyle})@restController#else@controller#end@requestmapping ( end/#if ($ {controlrermappingHyphenStyle}) $ {counterRermappingHyphen}#else $ {table.entitypath} #end ")#if ($ {superControllerClass}) Class $ {table.controllerName} يمتد $ {superControllerClass} {#elsepublic class $ {table.controllername} {#end private final logger = loggerfactory.getLogger ($ {table.controllername} .class) ؛ Autowired public $ {table.servicename} $ {table.entitypath} service ؛ /*** description: احصل على قائمة الترحيل* ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- احصل على $ {entity} قائمة ($ {entity} param ، requestparam (value = "draw" ، defaultValue = "0") integer draw ، @requestparam (value = "length") integer length ، @requestparam (value = "start") integer start) {datatablesjson <$} حاول {Integer Pageno = getPageno (ابدأ ، طول) ؛ الصفحة <$ {entity}> page = صفحة جديدة <$ {intity}> (pageno ، length) ؛ $ {table.entitypath} service.selectPage (صفحة ، entitywrapper جديد <$ {entity}> (param)) ؛ resjson.setdraw (draw ++) ؛ resjson.setRecorDstotal (page.getTotal ()) ؛ resjson.setRecordSfiltered (page.getTotal ()) ؛ resjson.setData (page.getRecords ()) ؛ Resjson.SetSuccess (صواب) ؛ } catch (استثناء e) {resjson.setsuccess (false) ؛ resjson.seterror ("معلومات الاستثناء: {"+e.getClass (). getName ()+"}") ؛ logger.info ("معلومات الاستثناء: {}"+e.getMessage ()) ؛ } إرجاع Resjson ؛ ستر ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id) {jsonresult <$ {entity}> resjson = new jsonresult <> () ؛ حاول {$ {entity} param = $ {table.entitypath} service.selectbyid (id) ؛ resjson.setData (param) ؛ Resjson.SetSuccess (صواب) ؛ } catch (استثناء e) {resjson.setsuccess (false) ؛ resjson.setMessage ("معلومات الاستثناء: {"+e.getClass (). getName ()+"}") ؛ logger.info ("معلومات الاستثناء: {}"+e.getMessage ()) ؛ } إرجاع Resjson ؛ } /** * description: حذف $ {intity} بواسطة ID * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- jsonresult <> () ؛ حاول {resjson.setsuccess ($ {table.entitypath} service.deleteById (id)) ؛ } catch (استثناء e) {resjson.setsuccess (false) ؛ resjson.setMessage ("معلومات الاستثناء: {"+e.getClass (). getName ()+"}") ؛ logger.info ("معلومات الاستثناء: {}"+e.getMessage ()) ؛ } إرجاع Resjson ؛ } /** * @description : Update ${entity} by id * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- @since : Create in $ {date} */ @requestmapping (value = "/ update $ {entity} byid" ، method = requestMethod.post) تحديث الكائن العام $ {entity} byid ($ {entity} param) {jsonresult <$ {entity}> resjson = new jsonresult <> () ؛ حاول {resjson.setsuccess ($ {table.entitypath} service.updateById (param)) ؛ } catch (استثناء e) {resjson.setsuccess (false) ؛ resjson.setMessage ("معلومات الاستثناء: {"+e.getClass (). getName ()+"}") ؛ logger.info ("معلومات الاستثناء: {}"+e.getMessage ()) ؛ } إرجاع Resjson ؛ } /** * description: إضافة $ {intity} * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- jsonresult <$ {entity}> resjson = new jsonresult <> () ؛ حاول {resjson.setsuccess ($ {table.entitypath} service.insert (param)) ؛ } catch (استثناء e) {resjson.setsuccess (false) ؛ resjson.setMessage ("معلومات الاستثناء: {"+e.getClass (). getName ()+"}") ؛ logger.info ("معلومات الاستثناء: {}"+e.getMessage ()) ؛ } إرجاع Resjson ؛ }}بالإضافة إلى هذا الملف ، أتابع الموقع الرسمي لقوالب الكود الأخرى. هنا أشير إلى 3 ملفات خارجية ، بما في ذلك AbstractController.java (فئة قاعدة التحكم) ، DatatablesJson.java و Jsonresult.java. ثم تشير هذه الملفات إلى الملفات الأخرى. كنت في حيرة من أمري. لماذا يوجد الكثير من الملفات؟ يبدو أنه إذا تم نشر جميعهم ، فسوف يستغرق الأمر مساحة أكبر. لذلك اخترت أن أؤمن بسحابة الكود. إذا كنت في حاجة إليها ، يرجى تنزيل Code Cloud وفقًا للملفات القليلة على Code Cloud. تجدر الإشارة إلى أن القوالب الخاصة بي يتم استبدالها مباشرة بواسطة دليل القوالب في MyBatis-plus.jar.
أخيرًا ، إنها عملية الاختبار
يتم وضع مقتطفات التعليمات البرمجية التالية في ملف وحدة التحكم ، ثم يتم تشغيل البرنامج ، يتوافق مع المنفذ ، وطريقة الطلب. للاختبار ، تحتاج إلى العمل وفقًا لفئة الكيان الخاصة بك ، لذلك هو للرجوع إليه فقط.
/** * صفحة ترقيم الصفحات */getMapping ("/test") صفحة عامة <Sether> test () {return orperService.SelectPage (صفحة جديدة <Sether> (0 ، 12)) ؛ }/*** AR اختبار جزئي*/getMapping ("/test1") صفحة عامة <Seter> test1 () {user user = new user () ؛ System.err.println ("حذف الكل:" + user.delete (null)) ؛ //user.setid(2017091801L) ؛ user.setAccout ("test"+num ++) ؛ user.settype ("اختبار") ؛ user.setCreateTime (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(); }这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。
最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!也希望大家多多支持武林网。