春のブーツは私にとって新しいものです。私の学習プロセス中、私はこのことがまだ簡単に始めることができることを発見しました。 Spring Bootが構成されていない場合、デフォルトでSpring Data JPAを使用します。このことは非常にシンプルなツールと言えますが、それでもMyBatisを使用することを好みます。最良のツールはありません。これだけが私に適しています。
MyBatisといえば、最近非常に便利なツールがあります-MyBatis -Plus(公式ウェブサイト)。更新されたバージョンは現在2.1.2になり、このバージョンもここで使用されています。私のお気に入りの機能は、コードジェネレーターと条件付きコンストラクターです。そのため、より簡単に開発できます。
MyBatisPlusの公式Webサイトには、スプリングブートの例があります。私はそれに従いましたが、プログラムは実行されませんでした。その後、デモで使用されるH2データベースはMySQLと同じではないことがわかりました。したがって、mybatisplusを統合したい場合は、公式ウェブサイトを見て迂回することはできません。
以下は統合プロセスです
1.最初に、必要なすべてのJARファイルを取得する必要があります。 pom.xmlに必要なものは次のとおりです
pom.xml(不完全)
<! - mybatis-plus begin-> <dependency> groupid> com.baomidou </groupid> <artifactid> mybatisplus-spring-boot-starter </artifactid> <バージョン> 1.0.4 </version <バージョン> 2.1.2 </version> </dependency> <dependency> groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-jdbc </artifactid> </dependency> <! - mybatis-plus end-> <! <GroupId> com.alibaba </groupId> <artifactid> druid </artifactid> <version> 1.1.3 </version> </dependency> <! - mysql-> <dependency> mysql </groupid> <artifactid> mysql-connector-Java </scope> <scope> <scope> <groupid> org.mybatis.spring.boot </groupid> <artifactid> mybatis-spring-boot-starter </artifactid> <バージョン> 1.3.1 </version> </dependency>
2.アカウント、パスワードなどのMyBatis関連の構成を追加します。ここでは、application.ymlを使用して一致させました。
Application.yml
サーバー:ポート:8080#Springspring:devtools:restart:enabled:enabled:true#これはホット展開用であり、Mybatis#データベース構成データソースとは関係ありません。 JDBC:mysql:// mysqldb:3306/tdx_shop?useunicode = true&charaterencoding = utf-8タイプ:com.alibaba.druid.druiddatasource#Hereはdruid接続プールを構成しています。以下はすべてドルイドフィルターの構成情報です:統計、壁、log4jマキシアクティブ:20イニシャルサイズ:1 maxwait:60000ミニドル:1 Timeevictionrunsmillis:60000 minevictionableidletimemillis:300000 validationquery:selece 'x' '' x '' 'x' testonborod:fals testonreturn:false testonreturn:false testonreturn:false testonreturn:false testonreturn:fals maxopenpreparedStatements:20 Connection-Properties:druid.stat.merggsql = ture; druid.stat.slowsqlmillis = 5000#mybatismybatis:mapper-locations:classpath*:/mapper/** mapper.xml#com.xx.mapperのxmlファイルを入力します。これは、リソース#Entityスキャンの下のマッパーです。複数のパッケージがコンマまたはセミコロンで区切られています。 Typealiasespackage:com.tdx.account_service.entity#これはエンティティクラスの場所です。
構成のものは、MyBatisで構成するために使用したものに似ていますが、Spring BootにはXML構成ファイルがありません。赤い文字の内容に注意してください。基本的に問題はありません。
3。MyBatis-Plus構成ファイル------ MyBatisPlusConfig。まず、上の図のファイルパスを説明しましょう。その中でも、mybatisplusconfigは構成フォルダーに配置され、XMLファイルはresoucesの下でマッパーに配置されます。
次に、mybatisplusconfigコンテンツの部分があります
mybatisproperties.java
パッケージ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.mybatisconfiguration; Import com.baomidou.mybatisplus.entity.globalConfiguration; Import com.baomidou.mybatisplus.enums.dbtype; com.baomidou.mybatisplus.plugins.pagination interceptor; Import com.baomidou.mybatisplus.plugins.performanceInterceptor; Import com.baomidou.mybatisplus.plugins.parser.isqlparser; Importcom.baomidou.mybatisplus.plugins.plugins.prmiduins.parmiduins.parmiduins.parmiduins.Prugins.Prugins.Prugins.Prugins.Prugins。 com.baomidou.mybatisplus.plugins.parser.tenanthandler; import com.baomidou.mybatisplus.plugins.parser.tenant.tenantsqlparser; Import com.baomidou.mybatisplus.spring.mybatissqlsessionsfactorybean; com.baomidou.mybatisplus.spring.boot.starter.springbootvfs; Import com.baomidou.mybatisplus.toolkit.pluginutils; import net.sf.jsqlparser.Expression.Expression; Import net.sf.jsqlparser.Expression.Lightression; org.apache.ibatis.databaseidprovider; Import org.apache.ibatis.mappedStatement; Import org.apache.ibatis.plugin.Interceptor; Import org.apache.ibatis.Reflection.metaObject; Import org.mybatis.Spring.Annotation.Mappcranscan; 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.servletrestrationbean; inmort org.springframed.context springframework.context.annotation.configuration; Import org.springframework.core.env.environment; Import org.springframework.core.io.defaultresourceloader; Import org.springframework.core.io.resourceleoader.spresframe. org.springframework.util.stringutils;インポートjavax.sql.datasource;インポートjava.sql.sqlexception;インポートjava.util.arraylist;インポートjava.util.list; ┳┛┳┛┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃┃ *┃ *┃┃beastの祝福 *┃┃┃┃┃┃┃┏┛ *┃ *┃┃ *┃ *┃ *┗┓┓┏━┳┓┏┛ *┃┫┫ *┃┫┫ *┗┻┛ * * @description:mybatisplus構成 * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- class MybatisPlusConfig { @Autowired private Environment environment;プライベートリラックスしたPropertyResolver PropertyResolver; @autowired private dataSource DataSource; @AutowiredプライベートMyBatisPropertiesプロパティ。 @autowired private resourceloader resourceloader = new defaultresourceloader(); @autowired(必須= false)プライベートインターセプター[]インターセプター。 @autowired(必須= false)プライベートデータベースadprovider databaseidprovider; /** * @description:mybatis-plus sql実行効率プラグイン[生産環境で閉じることができます] * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ @bean public DataSource Druiddatasource()Sthows Sqlexception {this.propertyResolver = new RelabedPropertyResolver(環境、 "Spring.DataSource。"); System.out.println( "========================================================================================= ================================================================================================ ==================================================================================================== ================================================================================================ DataSource.seturl( "url"))dataSource.setResolver.getProperty( "Driver-Class-Name")) dataSource.setInitialSize(integer.valueof( "initial-size")); DataSource.setMaxactive(integer.valueof( "max-active")); dataSource.setfilters( "filters"); -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- : Create in 2017/9/19 13:59 */ @Bean public PaginationIntercepter PaginationInterceptorページ= new paginecterceptor( "mysql")。 mybatissqlsessionfactorybean(){mybatissqlsessionbean mybatisplus = new mybatisplus.setdatasource(datasource.setvs( (Stringutils.hastext(this.properties.getConfiglocation()){mybatisplus.setConfiglocation(this.resourcerader.getConfiglocation()); (ObjectUtils.isempty(this.intercters){mybatisplus.setplugins(this.intercters); auto--> `0`("データベースID自己increment ")input->` 1`(user input id ")id_worker->` 2`( "global inited id")uuid-> `3`(" global inquine id ")globalconfig.setidtype(2); mybatisplus.setglobalconfig(mybatispurconfig(mybatisconfig); mybatisplus.setgloconfig); mybatisconfiguration(); (stringutils.haslength(this.properties.gettypealiasespackage()))){mybatisplus.settypealiasespackage(this.properties.gettypealiasespacage()); } if(stringutils.haslength(this.properties.gettypealiasespackage());} if(stringutils.haslerspackage()){mybatisplus.settypehandlerspackage(this.gettypehandlerspackage() (objectutils.isempty(this.properties.resolvemapperlocations){mybatisplus.setMapperlocations(this.properties.resolvemapperlocations()) druidstatviewservle(){//org.springframework.context.embedded.servletregistrationbeanは、登録のためにクラスを提供します// servletregistrationbean.addinitparameter( "lock"、 "127.0.0.1"); // servletregistration.addiniTparameter.addinitparameter(loginpassword」、「roots」を表示するために、アカウントのパスワードを表示します。 }/** * FilterRegistrationBean * */@bean Public RegistationBean Druidstatfilter()無視されます。これが完全な構成ファイルです。導入されたパッケージが間違っていないことに注意することが重要です!
4。また、DAOスキャンを有効にする必要があります。とても簡単です。 @mapperscan( "com.tdx.account_service.dao*")を起動ファイルに追加します。以下は完全なものです。
この時点で、構成は完了しており、実行後にプロジェクトを実行できます。
MyBatis-Plusはコードジェネレーターの最も楽しい部分だと思います。以下は、コードジェネレーターを使用するプロセスです
pom.xmlに何かを追加します
<Dependency> groupId> org.apache.velocity </groupid> <artifactid> velocity-engine-core </artifactid> <バージョン> 2.0 </version> </dependency>
1。コードジェネレーター構成ファイル
mybatisplusconfig.java
/*** Copyright(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.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;インポートcom.baomidou.mybatisplus.generator.config.templateconfig; Import com.baomidou.mybatisplus.generator.config.converts.mysqltypeconvert; Import com.baomidou.mybatisplus.generator.config.po.po.tablefill; com.baomidou.mybatisplus.generator.config.po.tableinfo; Import com.baomidou.mybatisplus.generator.config.rules.dbcolumntype; Import com.baomidou.mybatisplus.generator.config.rures.dbtype; Import; com.baomidou.mybatisplus.generator.config.rules.namingstrategy;/** *コードは、動物を保護するバグから遠く離れています。バグのないコード! *┃┗━━━┓ *┃ * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- packageName="account_service"; //ファイルパスprivate static string authorname = "liang.guangqing"; //著者private static string table = "sc_user"; //テーブル名private static string prefix = "sc_"; //テーブルプレフィックスprivate static file file = new file(packageName); private static string path = file.getabsolutepath(); public static void main(string [] args){// fill fill list <tablefill> tablefilllist = new ArrayList <>(); TableFillList.Add(new TableFill( "ASDD_SS"、fieldfill.insert_update)); //コードジェネレーターAutogenerator MPG = new Autogenerator()。setGlobalConfig(// Global Configuration New GlobalConfig().SetOutputDir(Path+"/src/main/java")// output directory.setFileOverRide(true)// XML Secondary Cache.SetBaseresultMap(True)// XML resultMap .setBaseColumnList(true)// xml columnlist .setopen(false)// Generation.setauthor(authorname)//ファイル名をカスタマイズします。 .SETXMLNAME( "%smapper").setservicename( "%sservice").setserviceimplname( "%sserviceimpl").setControllername( "%scontroller")).setDataSource(//データソース構成New DataSourfig()。 type.settypeconvert(new mysqltypeconvert(){//カスタマイズデータベーステーブルフィールドタイプ変換[オプション] @Override public dbcolumntype processtypeconvert(string fieldtype){system.out.println( "コンバージョンタイプ:" + fieldtype); // dbcolumntype.boolean; .seturl( "jdbc:mysql://127.0.0.1:3306/tdx_shop?charatereCoding = utf8")).setStrategy(//ポリシー構成new Strageyconfig()// .SetCapitalMode(True)//グローバルキャピタル/ naming.settableprefix(new String [] {freix})//ここでは、テーブルプレフィックスに変更できます。 string [] {"test"})//生成されたテーブルを除外します.setsupermapperclass( "com.baomidou.demo.testmapper")//カスタムサービス親クラス// .setsuperserviceclass( "com.baomidou.demo.testservice")//カスタムサービス実装クラス親クラス// .setsuperserviceimplclass( "com.baomidou.demo.demo.demo.demo.demo.demo.demo.demo.demo. class .setsupercontrollerclass( "com.tdx。"+packageName+"。Controller.AbstractController") {this.name = name; .SetEntityBoolEanColumnRemoveIsPrefix(true)// .SetRestControllerStyle(true)// .setControllerMappehyphenstyle(true)).SetPackeConfig(// packageconfig()// .setModulename( "user").setParent(com.tdx。 path.setController( "Controller")//ここにコントローラーパッケージ名、デフォルトWeb .setEntity( "Entity").setMapper( "dao").setservice( "service").setserviceimpl( "servic.impl")//.setxml( "mapper").setcfg(inject cums bay in cfg.ab.abcfg) injectionConfig(){@Override public void initmap(){object> new Hashmap <>( "ABC"、this.getConfig()。 } .setFileoutConfiglist(collects。<fileoutconfig> singletonList(new fileoutconfig( "/templates/mapper.xml.vm"){//カスタム出力ファイル@Override public string outputfile(tableinfo tableinfo){return path + "/src/mapper/" + " +" + " +" + " "mapper.xml";}}}))))))))。 src/setcontruller( "); .SetServiceImpl( "..."); //実行してmpg.execute()を生成します。 //注入設定を印刷すると、テンプレート[Noble] System.err.println(mpg.getcfg()。getMap()。get( "ABC"))で注入コンテンツを取得する方法を示します。 }}
ファイルにはまだ多くの変更があります。最も重要なことは、MySQLの接続情報です。アカウントとパスワードが間違っている理由はありません。あなたはそれに接続することができます。第二に、生成したテンプレートファイルのパスを設定します。ここで私が生成した道は、上の図で見ることができます。 com.tdx.account_serviceの下にあります。 XMLファイルはリソースの下に配置する必要があることに注意してください。そうしないと、この方法が見つからないと認識され、言われます。
公式ウェブサイトのコードテンプレートに従って生成されたファイルは、基本的に空白です。主な理由は、MyBatisプラスがパブリック方法を統合し、一般的に使用される多くのツールを参照できることです。ここでは、主に自分の習慣に従って、変更したcontroller.java.vmファイルを提供します。
controller.java.vm
Package $ {package.controller}; Import org.springframework.web.bind.annotation.RequestMapping; Import org.springframework.web.bind.annotation.RequestParam; #if($ {retscontrollerStyle})Import org.springframework.web.bbind.annotation 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} $ {package.entity} .common.datatablesjson; import $ {package.entity} .common.jsonresult; import $ {package.entity}。 ┃ *┃ *┗┳ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┃ *┗┓ * *┃┃ *┃ * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */#if($ {retscontrollerStyle})@restcontroller#else@controller#end@requestmapping( "#if($ {package.modulename})/$ {package.modulename}# end/#if($ {controllermappinghyphenstyle})$ {controllermappinghyphen}#else $ {table.entitypath}#end ") class $ {table.controllername}拡張$ {supercontrollerclass} {#elsepublic class $ {table.controllername} {#end private final logger 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")integer length、 @requestparam(value = "start")integer start) 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(例外e){resjson.setsuccess(false); resjson.setError( "例外情報:{"+e.getClass()。getName()+"}"); logger.info( "例外情報:{}"+e.getMessage()); } 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()); } Resjsonを返します。 } /** * @description:delete $ {entity} by id * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ jsonresult <>(); try {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)public object upputr upprod $ {entity} byid($ {entity} param){jsonresult <$ {entity}> resjson = new jsonult <>(); try {resjson.setsuccess($ {table.entitypath} service.updatebyid(param)); } catch(例外e){resjson.setsuccess(false); resjson.setMessage( "例外情報:{"+e.getClass()。getName()+"}"); logger.info( "例外情報:{}"+e.getMessage()); } 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()); } Resjsonを返します。 }}このファイルに加えて、他のコードテンプレートの公式Webサイトに従います。ここでは、AbstractController.java(コントローラーベースクラス)、datatablesjson.java、jsonresult.javaを含む3つの外部ファイルを参照してください。次に、これらのファイルは他のファイルを参照します。私は混乱しました。なぜそんなに多くのファイルがあるのですか?それらのすべてが投稿された場合、より多くのスペースを占めるようです。それで、私はコードクラウドを信じることにしました。必要な場合は、コードクラウド上のいくつかのファイルに従ってコードクラウドをダウンロードしてください。私のテンプレートは、mybatis-plus.jarのテンプレートディレクトリに直接置き換えられていることに注意してください。
最後に、それはテストプロセスです
次のコードスニペットがコントローラーファイルに配置され、ポートとリクエストメソッドに対応するプログラムが開始されます。テストのためには、自分のエンティティクラスに従って動作する必要があるため、参照専用です。
/** *ページネーションページ */@getMapping( "/test")public page <user> test(){return userservice.selectpage(new Page <user>(0、12)); }/*** ar partial test*/@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("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(); }这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。
最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!也希望大家多多支持武林网。