mybatis-plus (짧은 MP)는 mybatis 향상 도구입니다. Mybatis를 기반으로하면 개발을 단순화하고 효율성을 향상시키기 위해서만 향상되고 변하지 않으며 태어납니다.
중국어 문서 : http://baomidou.oschina.io/mybatis-plus-doc/#/
이 기사는 소개합니다
1) 구축 방법
2) 코드 생성 (컨트롤러, 서비스, 맵퍼, XML)
3) 단일 테이블의 CRUD, 조건부 쿼리 및 페이지 매김베이스 클래스가 완료되었습니다.
1. 그것을 구축하는 방법
1. 먼저 SpringBoot 프로젝트를 만듭니다 -> https://start.spring.io/
2. Maven 의존성
<pectionency> <groupid> com.baomidou </groupid> <artifactid> mybatis-plus-boot-starter </artifactid> <version> 2.3 </version> </fectionency> <!-코드 생성의 속도 종속성-> <groupid> org.apache.velocity </artifactid> valocity-engine-core-core-core- <버전> 2.0 </version> </fectionency>
3. 구성 (너무 말이 많다고 생각하기 때문에 데이터 소스의 구성이 여기에서 생략됩니다).
application.properties
mybatis-plus.mapper-locations = classpath : /mapper/*mapper.xmlmybatis-plus.typealiasespackage=com.taven.web.springbootmp.entitybatis-plus.global-config.id-type=3mype-plus.global-config.field-config egy = 2mybatis-plus.global-config.db-column-underline = truemybatis-plus.global-config.key-generator = com.baomidou.mybatisplus.incrementer.oracleKeyGeneratortormyBatis-plus.global-config.logic-delete-vallete-1 mybatis-plus.global-config.logic-not-delete-value = 0mybatis-plus.global-config.sql-injector = com.baomidou.mybatisplus.mapper.logicsqlinejector#클래스로 변경해야합니다. compig.meta-objector homefig.meta-objector .taven.web.springbootmp.mymetaobjecthandlermybatis-plus.configuration.map-underscore-to-camel-case = truemybatis-plus.configuration.cache-enabled = falsemybatis-plus.configuration.jdbc-for-null
구성 클래스 MyBatisPlusConfig
import org.mybatis.spring.annotation.mapperscan; import org.springframework.context.annotation.bean; import org.spramframework.context.annotation.configuration; import com.baomidou.mybatisplus.incrementer.h2keygenerator; import com.baomidou.mybatisplus.incrementer.ikeygenerator; import com.baomidou.mybatisplus.mapper.isqlinjector; import com.baomidou.mybatisplus.mapper.logicsqlinjector; import com.baomidou.mybatisplus.metabjecthandler; import com.baomidou.mybatisplus.plugins.paginationinterceptor; import com.baomidou.mybatisplus.plugins.performanceinterceptor; import com.taven.web.springbootmp.mymetaobjecthandler;@enableTransactionManagement@configuration@mapperscan ( "com.taven.web.springbootmp.mapper") 공개 클래스 MyBatisPlusConfig { / ** * MyBatis-Plus SQL Execution [ * / @BANTENTENTER SQL EXECTION IN CLAPETION IN CLASENE IN CLAPETIN PerformanceInterceptor PerformanceInterceptor () {return new PerformanceInterceptor (); } / * * Pagination 플러그인, 데이터베이스 유형에서 멀티 테넌트를 자동으로 식별하면 공식 웹 사이트 [플러그인 확장] * / @Bean Public Pagination Interceptor Pagination Interceptor () {return new Pagination Interceptor (); } @bean public metaobjecthandler metaobjecthandler () {return new mymetaobjecthandler (); } / *** 주입 기본 키 생성기* / @bean public ikeygenerator keygenerator () {return new h2keygenerator (); } / *** 주입 SQL 인젝터* / @bean public isqlinjector sqlinejector () {return new logicsqlinejector (); }} import com.baomidou.mybatisplus.mapper.metaobjecthandler; import org.apache.ibatis.reflection.metaobject; import org.slf4j.logger; import org.slf4j.loggerfactory;/** * 옵션 주입 방법 * // componoration -classion in appublic interection method * //@comporional inclic intomectance homeportory interection methods * // Metaobjecthandler {보호 된 최종 정적 로거 로그거 = loggerfactory.getLogger (application.class); @override public void insertfill (metaobject metaobject) {logger.info ( "추가 할 수없는 일을 할 수없는 일"); } @override public void updatefill (metaobject metaobject) {logger.info ( "업데이트 할 때 설명 할 수없는 일을하십시오"); }} 2. 코드 생성
Junit을 실행하여 컨트롤러, 서비스 인터페이스, 구현, Mapper 및 XML을 생성합니다.
import org.junit.test; import com.baomidou.mybatisplus.generator.agogenerator; import com.baomidou.mybatisplus.generator.config.config.datasourceconfig; import com.baomidou.mybatisplus.generator.config.globalconfig; 가져 오기; com.baomidou.mybatisplus.generator.config.packageconfig; import com.baomidou.mybatisplus.generator.config.strategyconfig; import com.baomidou.mybatisplus.generator.config.rules.dbtype; import com.baomidou.mybatisplus.generator.config.rules.namingstrategy;/** * <p> * 테스트 생성 코드 * </p> * * * @author k god * @date 2017/12/18 */public classeatorseratorserviceentity {@test public void generatecode () {string packagename = "com.taven.web.springbootmp"; 부울 servicenamestwithi = false; // user-> userervice, true로 설정 : user-> iuserservice generatebytables (servicenamestartwithi, packagename, "cable", "orde"); // 당신의 테이블 이름으로 수정} private void generatebytables (boolean servicenamestartwithi, string). = 새로운 GlobalConfig (); 문자열 dburl = "jdbc : mysql : // localhost : 3306/communicate"; DataSourceConfig DataSourceConfig = 새로운 DataSourceConfig (); DataSourceConfig.setdbtype (dbtype.mysql) .seturl (dburl) .setusername ( "root") .setpassword ( "root") .setdrivername ( "com.mysql.jdbc.driver"); StrategyConfig StrategyConfig = New StrategyConfig (); StrategyCapitalMode (true) .setentityLombokModel (false) .SetDBCOLUMNUNDERLINE (true) .SetNaming (namingStrategy.underline_to_camel) .setInclude (tableNames); // 여러 테이블 이름으로 수정하고 교체하고 배열 canceg.setAcce (false). .SetAuthor ( "Yin Tianwen") .setOutputDir ( "e : // dev // stsdev // spring-boot-mp // src // main // java") .setfileoverride (true); if (! servicenamestartwithi) {config.setserviceName ( "%sservice"); } new Autogenerator (). setGlobalConfig (config) .setDatasource (dataSourceConfig) .SetStrategy (StrategyConfig) .setPackageInfo (new packageConfig () .setParent (Packagename) .setController ( "컨트롤러"). } // private void generateByTables (String Packagename, String ... tabenames) {// generateByTables (true, packagename, tablemename); //}}이 시점에서 건축이 기본적으로 완료되었으며 아래에서 사용할 수 있습니다!
3. mybatis-plus를 사용하십시오
먼저, 위의 생성 코드 ()를 실행하고 테이블 구조에 따라 다음 코드를 생성합니다 (XML은 수동으로 XML로 이동). 서비스와 매퍼는 기본 클래스를 물려 받았으며 우리를위한 많은 방법을 캡슐화했습니다. 아래 몇 가지 간단한 예를 보겠습니다.
/** * <p> * 프론트 엔드 컨트롤러 * </p> * * @Author Yin Tianwen * @Since 2018-05-31 */ @Controller @requestMapping ( "/Cable") 공개 클래스 CableController {@autowired 개인 Cableservice Cableservice; /*** 목록 쿼리 테스트**/@requestmapping ( "/1") @ResponseBody public Object Test1 () {// 엔티티에 해당하는 EntityWrapper 개체 구성 및 필터 및 쿼리 ENTITYWRAPPER <cable> ew = 새 엔티티 wrapper <> (); ew.where ( "type = {0}", 1) .like ( "name", "king") 및 ( "core_number = {0}", 24) 및 ( "is_delete = 0"); 목록 <cable> list = cableservice.selectList (EW); List <map <string, object >> maps = cableservice.selectmaps (ew); System.out.println (목록); System.out.println (지도); "OK"를 반환합니다. }/*** Pagination Query test*/@requestmapping ( "/2") @ResponseBody public Object Test2 () {// 엔티티에 해당하는 EntityWrapper 객체를 작성하고 필터링 쿼리 엔티티 wrapper <cable> ew = new EntityWrapper <> (); ew.where ( "type = {0}", 1) //. 좋아요 ( "이름", "king") 및 ( "core_number = {0}", 24) 및 ( "is_delete = 0"); Page <cable> page = new Page <> (1,10); Page <cail> pagerst = cableservice.selectpage (page, ew); 반환 pagerst; }/*** 사용자 정의 쿼리 필드*/@requestmapping ( "/3") @ResponseBody public Object Test3 () {Object vl = null; // 엔티티에 해당하는 EntityWrapper 객체를 구성하고 필터링 쿼리 엔티티 wrapper <cable> ew = new EntityWrapper <> (); ew.setsqlselect ( "id,`name`," + "case type/n" + "way 1 way '220kv'/n" + "end typename") 페이지 <> (1,10); Page <cail> pagerst = cableservice.selectpage (page, ew); 반환 pagerst; }/** * 삽입 */@RequestMapping ( "/4") @ResponseBody public Object Test4 () {Cable C = New Cable (); c.setName ( "테스트 광학 케이블"); Cableservice.insert (C); "OK"를 반환합니다. }/** * 업데이트 */@requestmapping ( "/5") @ResponseBody Public Object Test5 () {Cable C = CableserVice.SelectById (22284L); C.SETNAME ( "테스트 광학 케이블 2222"); C. 세트 타입 (1); Cableservice.updatebyid (c); "OK"를 반환합니다. }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.