Spring Boot는 저에게 새로운 것입니다. 학습 과정에서 나는이 일이 여전히 시작하기 쉽다는 것을 알았습니다. Spring Boot가 구성되지 않으면 기본적으로 Spring Data JPA를 사용합니다. 이것은 매우 간단한 도구라고 할 수 있지만 여전히 mybatis를 사용하는 것을 선호합니다. 최상의 도구는 없습니다.이 도구만이 나에게 적합합니다.
Mybatis에 대해 말하면, 최근에 Mybatis -Plus (공식 웹 사이트)가 매우 유용한 도구가 있습니다. 업데이트 된 버전은 이제 2.1.2 이며이 버전도 여기에서도 사용됩니다. 내가 가장 좋아하는 기능은 코드 생성기 및 조건부 생성자로보다 쉽게 개발할 수 있습니다.
MyBatisPlus의 공식 웹 사이트에는 Spring Boot 예제가 있습니다. 나는 그것을 따랐고 프로그램은 실행되지 않았다. 나중에 Demo에서 사용하는 H2 데이터베이스가 MySQL과 같지 않다는 것을 알았습니다. 따라서 MyBatisPlus를 통합하려면 공식 웹 사이트를보고 우회를 피할 수 있습니다.
다음은 통합 프로세스입니다
1. 첫째, 필요한 모든 JAR 파일을 가져와야합니다. pom.xml에 필요한 것들은 다음과 같습니다
pom.xml (불완전)
<!-mybatis-plus 시작-> <pectionency> <groupid> com.baomidou </groupid> <artifactid> mybatisplus-spring-boot-starter </artifactid> <0.4 </version> </dependency> <groupid> com.baomidou </groupid> <artifactid> mybatis-plus <버전> 2.1.2 </version> </dependency> <pectomency> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-jdbc </artifactid> </dependency> <! <!-mybatis-plus end-> <!-Druid Alibaba 데이터베이저 연결 풀-> < <groupid> com.alibaba </groupid> <artifactid> druid </artifactid> <bersion> 1.1.3 </version> </dependency> <!-mysql-> <pectionency> <groupid> mysql </groupid> <artifactid> mysql-connector-java </artifactid> </scope> </scope> <groupid> org.mybatis.spring.boot </groupid> <artifactid> mybatis-spring-boot-starter </artifactid> <3.1 </version> </fectionency>
2. 계정, 비밀번호 등과 같은 MyBatis 관련 구성 추가. 여기서 Application.YML을 사용하여 일치했습니다.
application.yml
서버 : 포트 : 8080#Springspring : DevTools : Restart : enabled : true#this#hot deployment입니다. myBatis#database config dataSource : driver class-name : com.mysql.jdbc.driver username : root url : root url : root url : jdbc : mysql : // mysqldb : 3306/tdx_shop? useUnicode = true & charac 다음은 드루이드 필터에 대한 구성 정보입니다 : STAT, WALL, LOG4J MAXACTIVE : 20 이니셜 크기 : 1 MaxWait : 60000 Minidle : 1 TimeBetweengeevictionRunsmillis : 60000 MinevictableDeLletimemillis : 300000 검증 : 300000 검증 : True TesonBrest : False Poolperparedstatements : False Polleperparnements. MaxOpenPreperedStatements : 20 연결-프로파르티 : druid.stat.merggsql = ture; druid.stat.slowsqlmillis = 5000 #mybatismybatis : mapper-locations :/** mapper.xml #prut xml 파일을 찾을 수 있습니다. 다음은 자원 #ENTITY 스캔 하의 Mapper입니다. 여러 패키지가 쉼표 또는 세미콜론으로 분리됩니다. 변형 시설 스패 징지 : com.tdx.account_service.entity #엔티티 클래스 구성의 위치 : Map-underscore-to-Camel-Case : True Cache-enabled : False #LoggingLogging : level : warn
구성 재료는 MyBatis로 구성하는 데 사용한 것과 유사하지만 Spring Boot에는 XML 구성 파일이 없습니다. 빨간 문자의 내용에주의를 기울이면 기본적으로 문제가 없습니다.
3. MyBatis-Plus 구성 파일 ------ MyBatisPlusConfig. 먼저 위 그림의 파일 경로를 설명해 봅시다. 그중에서도 MyBatisPlusConfig는 구성 폴더에 배치되며 XML 파일은 Resouces의 Mapper에 배치됩니다.
그런 다음 mybatisplusconfig 컨텐츠 부분이 있습니다
mybatisproperties.java
pack com.baomidou.mybatisplus.mybatisconfiguration; import com.baomidou.mybatisplus.mybatisconfiguration; import com.baomidou.mybatisplus.entity.globalconfiguration; import com.baomidou.mybatisplus.enums.dbtype; com.baomidou.mybatisplus.plugins.paginationinterceptor; import com.baomidou.mybatisplus.plugins.performanceinterceptor; import com.baomidou.mybatisplus.plugins.parser.isqlparser; import com.baomidou.mybatisplus.sparser.isqlparser com.baomidou.mybatisplus.plugins.parser.tenant.tenanthandler; import com.baomidou.mybatisplus.plugins.parser.tenant.tenantsqlparser; import com.baomidou.mybatisplus.mybatissqlsectorybean; import com.baomidou.mybatisplus.spring.boot.starter.springbootvfs; import com.baomidou.mybatisplus.toolkit.pluginutils; import net.sf.jsqlparser.expression; import net.sf.jsqlparser.expression.longvalue; 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.mappercan; org.mybatis.spring.spring.boot.autoconfigure.mybatisproperties; import org.springframework.bean.beans.antoration.aUtowired; import org.spramframework.boot.bind.relaxedPropertyresolver; import org.springframework.boot.context.properties.enableconfigurationProperties; import org.springframework.boot.web.servlet.filterregistrationbean; import org.springframework.boot.web.servlet.servletretrationbean; import org.spram.spring org.springframework.context.annotation.configuration; import org.springframework.core.env.environment; import org.springframework.core.io.defaultresourceloader; import org.spramework.core.io.resourceler; import org.spram.spram.spring org org.springframework.util.stringutils; import javax.sql.datasource; import java.sql.sqlexception; import java.util.arraylist import java.util.arraylist;/** * 코드는 동물 보호와 함께 멀리 떨어져 있습니다. ┳┛ ┗┳ ┃ * ┃ ┃ * ┃ ┃ * ┃ ┗┳ ┃ * ┃ ┃ * ┃ ┗┓ ┏━┛ * ┃ ┃ ┃ Bless of the beast* ┃ ┃ ┃ ┃ ┃ ┃ ┗┓ ┏┛ * ┃ ┃ ┃ Bless of the beast* ┃ ┃ ┃ ┃ ┃ ┃ No bugs! * ┃ ┃ * ┃ ┣┓ * ┃ * ┏┛ * ┗┓┓┏━┳┓┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * @description : mybatisplus 구성 * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- class MybatisPlusConfig { @Autowired private Environment environment; Private RelaxeDpropertyresolver PropertyResolver; @autowired Private DataSource DataSource; @autowired 개인 mybatisproperties 속성; @autowired private resourceloader resourceloader = new defaultresourceloader (); @autowired (필수 = 거짓) 개인 요격기 [] 인터셉터; @autowired (필수 = false) private databaseidprovider databaseidprovider; /** * @Description : MyBatis-Plus SQL 실행 효율성 플러그인 [생산 환경에서 닫을 수 있습니다] * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ @bean public dataSource druiddatasource ()는 sqlexception {this.propertyresolver = New RestendPropertyresolver (환경, "spring.datasource"); System.out.println ( "=========================================================================================================== =================================================================================================================================================== ========================================================================================================================== =================================================================================================================================================== DataSource.SetUrl (PropertyResolver.getProperty ( "url"); DataSource.setPassword (PropertyResolver.getProperty ( "Password")); DataSource.setMaxwait (long.valueof (PropertyResolver.getProperty ( "max-wait"))); DataSource.setMinevictableDletimemillis (PropertyResolver.getProperty ( "min-evictable-idle-time-millis")); } /** * @Description : mybatis-plus pagination plugin* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- : 2017/9/19 13:59*/@bean public pagination interceptor pagination interceptor (pageination interceptor page = page.setdialecttype); */ bean public mybatissqlsectionbean mybatissqlsessionfactorybean (mybatissqlsessionfactorybean mybatisplus) (stringUtils.Hastext (this.properties.getConfigLocation ())) {mybatisplus.setConfigLocation (this.resourceloader.getResource (this.properties.getConfigLocation ()); (! isember.isempty (this.interceptor) {mybatisplus.setplugins (this.interceptors); auto->`0` ( "데이터베이스 ID 자체 증가 mybatisconfiguration () MC. (StringUtil.haslength (this.properties.getTypealiasEspackage ())) {myBatisPlus.setTypealiasEspackage (this.properties.getTypealiasEspackage ()); } if (stringUtils.haslength (this.properties.getTypealiasEspackage ());} if (stringUtils.haslength (this.properties.getTypeHandlersPackage ()) {myBatisPlus.SetTypeHandlerspackage (this.properties.getTypePeAchage ()); (! ObjectUls.isempty (this.properties.resolveMapperLocations ())) {myBatisPlus.setMapperLocations (this.properties.ResolVemapperLocations ()); druidstatviewservle () {//org.springframework.context.embedded.servletregistrationbean은 servletregistrationbean servletregistrationbean을 제공합니다. servletretrationbean.addinitparameter ( "허용", "127.0.0.1"); ServletregistrationBean.AddinitParameter ( "LoginPassword", "root"; FilterRegationBean */@bean public filtergistrationbean druidstatfilter (filterregistrationbean filterregistrationbean) (new WebStatfilter ()) FilterRegrationBean.AddInitParameter ( "제외", ".다음은 전체 구성 파일입니다. 소개 된 패키지가 잘못되지 않았다는 점에 유의해야합니다!
4. 또한 DAO 스캔을 활성화해야합니다. 매우 간단합니다. 시작 파일에 @mapperscan ( "com.tdx.account_service.dao*")을 추가하십시오. 다음은 완전한 것입니다.
이 시점에서 구성이 완료되었으며 프로젝트를 실행 한 후 프로젝트를 실행할 수 있습니다.
Mybatis-Plus가 코드 생성기의 가장 재미있는 부분이라고 생각합니다. 다음은 코드 생성기 사용 프로세스입니다.
pom.xml에 무언가를 추가하십시오
<pectionency> <groupid> org.apache.velocity </groupid> <artifactid> Velocity-Engine-Core </artifactid> <bersion> 2.0 </version> </fectionency>
1. 코드 생성기 구성 파일
mybatisplusconfig.java
/*** 저작권 (c) 2011-2016, hubin ([email protected]). * <p> * Apache 라이센스에 따라 라이센스가 부여 된 버전 2.0 ( "라이센스"); 라이센스를 준수하는 것 외에는이 파일을 사용할 수 없습니다. 귀하는 * <p> * http://www.apache.org/license/license/license-2.0 * <p> *에서 * 라이센스 사본을 얻을 수 있으며, 해당 법률에 의해 요구되거나 서면으로 동의하지 않는 한, 라이센스에 따라 배포 된 소프트웨어 *는 명시 적 또는 묵시적으로 "대신"보증 또는 조건없이 "IS"기준으로 배포됩니다. 라이센스에 따른 * 권한 및 제한에 관한 특정 언어에 대한 * 라이센스를 참조하십시오. */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 com.baomidou.mybatisplus.generator.agogenerator; import com.baomidou.mybatisplus.generator.injectionconfig; import com.baomidou.mybatisplus.generator.config.datasourceconfig; import com.baomidou.mybatisplus.generator.config.fileoutcoconfig; com.baomidou.mybatisplus.generator.config.globalconfig; import com.baomidou.mybatisplus.generator.config.packageconfig; import 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; import com.baomidou.mybatisplus.generator.config.rules.dbcolumntype; import com.baomidou.mybatisplus.generator.config.rules.dbtype; com.baomidou.mybatisplus.generator.config.rules.rules.namingstrategy;/** *코드는 동물 보호와 함께 버그에서 멀리 떨어져 있습니다 *┏┓ ┏┓ *┏┛━━━━━━━┛┻┓ *┃ ┃ *┃ ━ ┃ *┃ ┳┛ ┗┳ ┃ ┃ *┃ ┃ *┃ *┃ ┃ *┃ *┗━┓ ┏━┛ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ * 버그! * ┃ ┃ * ┃ ┣┓ * ┃ * ┏┛ * ┗┓┓┏━┳┓┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ ┃┫┫ * ┗┻┛ * * @description : mybatisplus 코드 생성기 * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- packageName="account_service"; // 파일 경로 개인 정적 문자열 authorname = "liang.guangqing"; // 저자 개인 정적 문자열 테이블 = "sc_user"; // 테이블 이름 개인 정적 문자열 접두사 = "SC_"; // 테이블 접두사 개인 정적 파일 파일 = 새 파일 (packagename); 개인 정적 문자열 경로 = file.getabsolutepath (); public static void main (string [] args) {// 채워야하는 필드를 사용자 정의합니다. 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) // 파일을 덮어 쓰는 것인지 (true) // enave actubecord. XML Secondary Cache.setBaseresultMap (true) // xml resultmap .setbasecolumnlist (true) // xml columnlist. .setxmlname ( "%smapper") .setServiceName ( "%sservice") .setServiceimplname ( "%sserviceimpl") .setControllerName ( "%scontroller") .setDataSource (// data source new dataSourceConfig () .SETDBTYPE (dBTYPEPL). type.settypeconvert (new mysqltypeconvert () {// 데이터베이스 테이블 필드 유형 변환 [옵션] @override public dbcolumntype processTypeconvert (string fieldType) {system.out.println ( "변환 유형 :" + fieldtype); // if (fieldType.tolowercase ()). // return dbcolumntype.boolean} return super.processtypeconvert (fieldtype)). .SetUrl ( "JDBC : mysql : //127.0.0.1 : 3306/tdx_shop? characterEncoding = utf8") .setStrategy (// 정책 구성 New StrategyConfig () // 전 세계 자본화 naming //.setdbcolundunderline) //trobal anderline naming (. naming.settableprefix (new string [] {prefix}) // 여기서 여기에서 테이블 prefix.setnaming (namingstrategy.underline_to_camel) // 테이블 이름 생성 전략을 수정할 수 있습니다. String [] { "test"}) // 생성 된 테이블 제외 // 사용자 정의 Entity Parent Class // .SetSuperEntityClass ( "com.baomidou.demo.testentity") // 사용자 정의 엔티티, 공개 필드 //.setSuperentityColumns(New String [] { "test_id"}). .SetSuperMapperClass ( "com.baomidou.demo.testmapper") // 사용자 정의 부모 클래스 // .SetSuperserviceClass ( "com.baomidou.demo.testService") // 사용자 정의 서비스 구현 클래스 상위 클래스 // .setsuperserviceimplass ( "com.baomidou.demo.demo.demo.demo. .SetSuperControllerClass ( "com.tdx."+packagename+". controller.abstractController") // [Entity] 필드 상수를 생성 할 것인지 (기본적으로 false) // public static final string id = "test_id"; {this.name = name; // .SetEntityBooleanColumnRemoveISPrefix (true) // .setRestControllersTyle (true) // .setControllerMpappingHyphenStyle (true)) .setPackageInfo (// packageConfig ( "user") .setParent ( "+tdx."+tdx. " Path.setController ( "Controller") // 여기에 컨트롤러 패키지 이름, Default Web .Setentity ( "Entity") .setMapper ( "dao") .SetService ( "service") .setServiceImpl ( "service.impl") //.setxml (”mapper ") .setcfg (// injject concliguration)가 있습니다. iniversityconfig () {@override public void initmap () {map <string, object> map.put ( "abc", getconfig (). getauthor () + "-mp"; } .setFileOutConfigList (컬렉션. <fileoutConfig> SingletonList (새 FileOutConfig ( "/templates/mapper.xml.vm") {// 사용자 정의 출력 파일 디렉토리 @override public string outputfile (tableInfo tableInfo) {return path + "/src/main/resources/") "mapper.xml"))) .settemplate (// 기본 XML 생성을 끄고 생성을 루트 디렉토리로 조정하십시오. new templateconfig (). 템플릿 구성을 사용자 정의하십시오. 템플릿은 다음과 같이 사용자 정의 할 수 있습니다. // mpg.execute ()를 생성하려면 실행합니다. // 주입 설정을 인쇄합니다. 여기에서 템플릿 [noble] system.err.println (mpg.getcfg (). getMap (). get ( "abc")에서 주입 내용을 가져 오는 방법을 보여줍니다. }}
파일에는 여전히 많은 수정이 있습니다. 가장 중요한 것은 MySQL의 연결 정보입니다. 계정과 비밀번호가 잘못된 이유는 없습니다. 연결할 수 있습니다. 둘째, 생성 한 템플릿 파일의 경로를 설정하십시오. 여기서 생성 한 경로는 위 그림에서 볼 수 있습니다. com.tdx.account_service 아래에 있습니다. XML 파일은 리소스 아래에 배치되어야합니다. 그렇지 않으면이 방법을 찾을 수 없다고 인식 할 수 있습니다.
공식 웹 사이트의 코드 템플릿에 따라 생성 된 파일은 기본적으로 비어 있습니다. 주된 이유는 Mybatis-Plus가 공개 방법을 통합하고 일반적으로 사용되는 많은 도구를 참조 할 수 있기 때문입니다. 여기에서는 컨트롤러를 제공합니다. java.vm 파일은 주로 내 자신의 습관에 따라 수정했습니다.
Controller.java.vm
package $ {package.controller}; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.bind.annotation.requestparam; #if (restontrollerstyle}) import org.springframework.westmethod.annot.annot.annot.annot org.springframework.web.bind.annotation.restController; #ELSeimport org.spramframework.steretype.controller;#end#if ($ {superControllerClassPackage}) import $ {superControllerClassPackage}; en endimport org.spring com.baomidou.mybatisplus.mapper.entityWrapper; import com.baomidou.mybatisplus.plugins.page; import $ {package.service}. $ {table.servicename}; import $ {package.entity} .common.datatablesson; import $ {package.common.comentity} $ {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 ($ {controllerMappingHyphenStyle}) $ {ControlLerMpappingHyphen}#else $ {table.entityPath} #end ")#if ($ {superControllerClass}) public 클래스 $ {table.controllername} 확장 $ {SuperControllerClass} {#ELSePublic Class $ {table.controllerName} {#end private final logger = loggerfactory.getLogger ($ {table.controllerName} .class); @autowired public $ {table.servicename} $ {table.entitypath} service; /*** @description : 페이징 목록 가져 오기* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- RequestMethod.POST) public Object get $ {entity} list ($ {entity} param, @requestparam (value = "draw", defaultValue = "0") Integer Draw, @requestparam (value = "length") 정수 길이, @requestparam (value = "start") {datatables json <$}> new Datatblesjson <); try {Integer pageno = getpageno (시작, 길이); 페이지 <$ {entity}> page = 새 페이지 <$ {entity}> (pageno, length); $ {table.entityPath} service.selectPage (페이지, 새 엔티티 wrapper <$ {entity}> (param)); resjson.setdraw (draw ++); resjson.setRecordStotal (page.getTotal ()); resjson.setRecordSfiltered (page.getTotal ()); resjson.setData (page.getRecords ()); resjson.setSuccess (true); } catch (예외 e) {resjson.setSuccess (false); resjson.seterror ( "예외 정보 : {"+e.getClass (). getName ()+"}"); logger.info ( "예외 정보 : {}"+e.getMessage ()); } return resjson; } /** * @description : get $ {entity} by id * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Object get${entity}ById(String id) {jsonresult <$ {entity}> resjson = new JsonResult <> (); {$ {entity} param = $ {table.entityPath} service.SelectById (id); resjson.setData (param); resjson.setSuccess (true); } catch (예외 e) {resjson.setSuccess (false); resjson.setMessage ( "예외 정보 : {"+e.getClass (). getName ()+"}"); logger.info ( "예외 정보 : {}"+e.getMessage ()); } return resjson; } /** * @description : id * by id * delete $ {entity} ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ jsonresult <> (); try {resjson.setsuccess ($ {table.entityPath} service.deleteByid (id)); } catch (예외 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 = "/ update $ {entity} byid", method = requestmethod.post) public 객체 업데이트 $ {entity} byid ($ {entity} param) {entity}> resjson = new Jsonresult <> (); try {resjson.setsuccess ($ {table.entityPath} service.updateByid (param)); } catch (예외 e) {resjson.setSuccess (false); resjson.setMessage ( "예외 정보 : {"+e.getClass (). getName ()+"}"); logger.info ( "예외 정보 : {}"+e.getMessage ()); } return resjson; } /** * @description : 추가 $ {entity} * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- param) { jsonresult <$ {entity}> resjson = new jsonresult <> (); try {resjson.setsuccess ($ {table.entityPath} service.insert (param)); } catch (예외 e) {resjson.setSuccess (false); resjson.setMessage ( "예외 정보 : {"+e.getClass (). getName ()+"}"); logger.info ( "예외 정보 : {}"+e.getMessage ()); } return resjson; }}이 파일 외에도 다른 코드 템플릿의 공식 웹 사이트를 따릅니다. 여기에서 AbstractController.java (컨트롤러 기본 클래스), DatatablesJson.java 및 JsonResult.java를 포함한 3 개의 외부 파일을 참조하십시오. 그런 다음이 파일은 다른 파일을 나타냅니다. 나는 혼란 스러웠다. 파일이 왜 그렇게 많은가? 그들 모두가 게시되면 더 많은 공간을 차지할 것 같습니다. 그래서 나는 코드 클라우드를 믿기로 결정했습니다. 필요한 경우 Code Cloud의 몇 가지 파일에 따라 Code Cloud를 다운로드하십시오. 내 템플릿은 mybatis-plus.jar의 템플릿 디렉토리로 직접 대체됩니다.
마지막으로 테스트 과정입니다
다음 코드 스 니펫은 컨트롤러 파일에 배치 된 다음 포트 및 요청 메소드에 해당하는 프로그램이 시작됩니다. 테스트를 위해서는 자신의 엔티티 클래스에 따라 작동해야하므로 참조용입니다.
/** * Pagination Page */@getMapping ( "/test") public page <user> test () {return userervice.selectpage (새 페이지 <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 ( "테스트"+num ++); user.settype ( "테스트"); user.setcreateTime (새 날짜 ()); 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(); }这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。
最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!也希望大家多多支持武林网。