当前位置: 首页>后端>正文

你还没用过Mybatis-Plus?丝般顺滑,快速上手!

涓€銆佹杩?/h2>
你还没用过Mybatis-Plus?丝般顺滑,快速上手!,第1张

1.1銆佷粈涔堟槸MyBatis-Plus

MyBatis-Plus (opens new window)锛堢畝绉?MP锛夋槸涓€涓?MyBatis (opens new window)鐨勫寮哄伐鍏凤紝鍦?MyBatis 鐨勫熀纭€涓?code>鍙仛澧炲己涓嶅仛鏀瑰彉锛屼负绠€鍖栧紑鍙戙€佹彁楂樻晥鐜囪€岀敓銆?/p>

1.2銆佺壒鎬?/h2>
  • 鏃犱镜鍏?/strong>锛氬彧鍋氬寮轰笉鍋氭敼鍙橈紝寮曞叆瀹冧笉浼氬鐜版湁宸ョ▼浜х敓褰卞搷锛屽涓濊埇椤烘粦
  • 鎹熻€楀皬锛氬惎鍔ㄥ嵆浼氳嚜鍔ㄦ敞鍏ュ熀鏈?CURD锛屾€ц兘鍩烘湰鏃犳崯鑰楋紝鐩存帴闈㈠悜瀵硅薄鎿嶄綔
  • 寮哄ぇ鐨?CRUD 鎿嶄綔锛氬唴缃€氱敤 Mapper銆侀€氱敤 Service锛屼粎浠呴€氳繃灏戦噺閰嶇疆鍗冲彲瀹炵幇鍗曡〃澶ч儴鍒?CRUD 鎿嶄綔锛屾洿鏈夊己澶х殑鏉′欢鏋勯€犲櫒锛屾弧瓒冲悇绫讳娇鐢ㄩ渶姹?/li>
  • 鏀寔 Lambda 褰㈠紡璋冪敤锛氶€氳繃 Lambda 琛ㄨ揪寮忥紝鏂逛究鐨勭紪鍐欏悇绫绘煡璇㈡潯浠讹紝鏃犻渶鍐嶆媴蹇冨瓧娈靛啓閿?/li>
  • 鏀寔涓婚敭鑷姩鐢熸垚锛氭敮鎸佸杈?4 绉嶄富閿瓥鐣ワ紙鍐呭惈鍒嗗竷寮忓敮涓€ ID 鐢熸垚鍣?- Sequence锛夛紝鍙嚜鐢遍厤缃紝瀹岀編瑙e喅涓婚敭闂
  • 鏀寔 ActiveRecord 妯″紡锛氭敮鎸?ActiveRecord 褰㈠紡璋冪敤锛屽疄浣撶被鍙渶缁ф壙 Model 绫诲嵆鍙繘琛屽己澶х殑 CRUD 鎿嶄綔
  • 鏀寔鑷畾涔夊叏灞€閫氱敤鎿嶄綔锛氭敮鎸佸叏灞€閫氱敤鏂规硶娉ㄥ叆锛?Write once, use anywhere 锛?/li>
  • 鍐呯疆浠g爜鐢熸垚鍣?/strong>锛氶噰鐢ㄤ唬鐮佹垨鑰?Maven 鎻掍欢鍙揩閫熺敓鎴?Mapper 銆?Model 銆?Service 銆?Controller 灞備唬鐮侊紝鏀寔妯℃澘寮曟搸锛屾洿鏈夎秴澶氳嚜瀹氫箟閰嶇疆绛夋偍鏉ヤ娇鐢?/li>
  • 鍐呯疆鍒嗛〉鎻掍欢锛氬熀浜?MyBatis 鐗╃悊鍒嗛〉锛屽紑鍙戣€呮棤闇€鍏冲績鍏蜂綋鎿嶄綔锛岄厤缃ソ鎻掍欢涔嬪悗锛屽啓鍒嗛〉绛夊悓浜庢櫘閫?List 鏌ヨ
  • 鍒嗛〉鎻掍欢鏀寔澶氱鏁版嵁搴?/strong>锛氭敮鎸?MySQL銆丮ariaDB銆丱racle銆丏B2銆丠2銆丠SQL銆丼QLite銆丳ostgre銆丼QLServer 绛夊绉嶆暟鎹簱
  • 鍐呯疆鎬ц兘鍒嗘瀽鎻掍欢锛氬彲杈撳嚭 SQL 璇彞浠ュ強鍏舵墽琛屾椂闂达紝寤鸿寮€鍙戞祴璇曟椂鍚敤璇ュ姛鑳斤紝鑳藉揩閫熸彧鍑烘參鏌ヨ
  • 鍐呯疆鍏ㄥ眬鎷︽埅鎻掍欢锛氭彁渚涘叏琛?delete 銆?update 鎿嶄綔鏅鸿兘鍒嗘瀽闃绘柇锛屼篃鍙嚜瀹氫箟鎷︽埅瑙勫垯锛岄闃茶鎿嶄綔

1.3銆佹敮鎸佹暟鎹簱

浠讳綍鑳戒娇鐢?MyBatis 杩涜 CRUD, 骞朵笖鏀寔鏍囧噯 SQL 鐨勬暟鎹簱锛屽叿浣撴敮鎸佹儏鍐靛涓嬶紝濡傛灉涓嶅湪涓嬪垪琛ㄦ煡鐪嬪垎椤甸儴鍒嗘暀绋?PR 鎮ㄧ殑鏀寔銆?/p>

  • MySQL锛孫racle锛孌B2锛孒2锛孒SQL锛孲QLite锛孭ostgreSQL锛孲QLServer锛孭hoenix锛孏auss 锛孋lickHouse锛孲ybase锛孫ceanBase锛孎irebird锛孋ubrid锛孏oldilocks锛宑siidb
  • 杈炬ⅵ鏁版嵁搴擄紝铏氳胺鏁版嵁搴擄紝浜哄ぇ閲戜粨鏁版嵁搴擄紝鍗楀ぇ閫氱敤(鍗庡簱)鏁版嵁搴擄紝鍗楀ぇ閫氱敤鏁版嵁搴擄紝绁為€氭暟鎹簱锛岀€氶珮鏁版嵁搴?/li>

1.4銆佹鏋剁粨鏋?/h2>
你还没用过Mybatis-Plus?丝般顺滑,快速上手!,第2张

浜屻€佸揩閫熼泦鎴?/h2>

2.1銆丼pringBoot椤圭洰蹇€熼泦鎴?/h2>

濡傛灉浣犵殑椤圭洰宸茬粡閰嶇疆浜哅yBatis锛岄偅涔堬紝浣犲彧闇€

1銆佸紩鍏ybatis-plus渚濊禆锛?code>鏇挎崲鎺?/code>mybatis鐨勪緷璧?/p>

2銆佸皢application閰嶇疆涓殑mybatis鏀逛负mybatis-plus鍗冲彲

  • 寮曞叆渚濊禆

     <dependencies>
         <dependency>
             <groupId>com.baomidou</groupId>
             <artifactId>mybatis-plus-boot-starter</artifactId>
             <version>鏈€鏂扮増鏈?lt;/version>
         </dependency>
     </dependencies>
    
    
  • application淇敼閰嶇疆

     mybatis-plus:
       mapper-locations: xxx
       executor-type: simple
       configuration:
         log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
    
    

2.2銆丮yBatis-Plus绫荤殑鐗规畩瀹氫箟

MyBatis-Plus鍒嗗埆瀵筍ervice灞傘€丮apper灞傛彁渚涗簡鍔熻兘鎷撳睍

鎯宠浣跨敤MyBatis-Plus鍐呯疆鐨勬柟娉曪紝闇€瑕佸疄鐜癕yBatis-Plus鐨勭壒娈婃帴鍙?/p>

  • Service灞?/strong>

     // service鎺ュ彛闇€瑕佺户鎵縄Service<User>鎺ュ彛
     public interface UserService extends IService<User> {
     
     }
     
     // service瀹炵幇绫婚渶瑕佺户鎵縎erviceImpl<UserMapper, User>鎺ュ彛
     public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
     
     }
    
    
  • Mapper灞?/strong>

     // 闇€瑕佺户鎵緽aseMapper<User>鎺ュ彛
     public interface UserMapper extends BaseMapper<User> {
     
     }
    
    

涓夈€丆RUD Boy

3.1銆丆RUD

瀵逛簬CRUD锛孧yBatis-Plus鎻愪緵浜嗕袱绫绘帴鍙o細Service灞傘€丮apper灞傘€傚姛鑳戒竴鏍凤紝涓嶅悓灞傛湁涓嶅悓鐨勬柟娉曘€?/p>

銆怱ervice灞傘€?/p>

 private finally MyService myService;
 // 淇濆瓨鐢ㄦ埛锛圫ervice CRUD锛?
 myService.save(User);

銆怣apper灞傘€?/p>

 private finally MyMapper myMapper;
 // 淇濆瓨鐢ㄦ埛锛圡apper CRUD锛?
 myMapper.insert(User);

  • 浣跨敤绀轰緥

     // 鍗曚釜鏌ヨ
     User user = userMapper.selectById(id);
     // 鎵归噺鏌ヨ
     List<User> users =  userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
     // 鏉′欢鏌ヨ
     HashMap<String, Object> map = new HashMap();
     map.put("name", "鍗佸勾");
     map.put("age", 12);
     userMapper.selectByMap(map);
    
    
  • 鏇村鎿嶄綔

    MyBatis-Plus瀹樻柟鏂囨。-CRUD

3.2銆佹潯浠舵瀯閫犲櫒

Mybatis鎻愪緵浜哘ueryWrapper锛屽彲浠ヨ鎴戜滑鑷畾涔夎緝涓哄鏉傜殑sql鏌ヨ鏉′欢

馃摙

涓嶆敮鎸佷互鍙婁笉璧炴垚鍦?RPC 璋冪敤涓妸 Wrapper 杩涜浼犺緭

  1. wrapper 寰堥噸
  2. 浼犺緭 wrapper 鍙互绫绘瘮涓轰綘鐨?controller 鐢?map 鎺ユ敹鍊?寮€鍙戜竴鏃剁埥,缁存姢鐏懍鍦?
  3. 姝g‘鐨?RPC 璋冪敤濮垮娍鏄啓涓€涓?DTO 杩涜浼犺緭,琚皟鐢ㄦ柟鍐嶆牴鎹?DTO 鎵ц鐩稿簲鐨勬搷浣?/li>
  4. 鎴戜滑鎷掔粷鎺ュ彈浠讳綍鍏充簬 RPC 浼犺緭 Wrapper 鎶ラ敊鐩稿叧鐨?issue 鐢氳嚦 pr
  • 浣跨敤绀轰緥

     QueryWrapper<User> wrapper = new QueryWrapper<>();
     wrapper.isNotNull("name")
       .ge("age", 12) // 骞撮緞灏忎簬12鐨?
       .notLike("name", "e") // and name not like '%e%'
       .likeRight("name", "est") // and name like 'est%
       .likeLeft("name", "est") // and name like '%est'
       .inSql("id", "select id from user where id < 3") // and id in (select id from user where id < 3)
       .orderByAsc("id");// 鏍规嵁id姝e簭
     List<User> users = userMapper.selectList(wrapper);
    
    
  • 鏇村鍙傝€?/strong>

    MyBatis-Plus瀹樻柟鏂囨。-鏉′欢鏋勯€犲櫒

3.3銆佷富閿瓥鐣?/h2>

Mybatis-Plus鎻愪緵浜嗗绉嶄富閿瓥鐣?/p>

 public enum IdType {
     AUTO(0), // 鏁版嵁搴搃d鑷
     NONE(1), // 鏈缃富閿?
     INPUT(2), // 鎵嬪姩杈撳叆
     ASSIGN_ID(3), // 榛樿鐨勫叏灞€鍞竴id锛堥洩鑺辩畻娉曪級
     ASSIGN_UUID(4); // uuid
 
     private final int key;
 
     private IdType(int key) {
         this.key = key;
     }
 
     public int getKey() {
         return this.key;
     }
 }

3.3.1銆佸熀鏈娇鐢?/h3>

姣斿Mysql鏁版嵁搴擄紝鍦ㄥ畾涔夎〃鐨勬椂鍊欙紝瀛楁鍙互鐩存帴璁剧疆鑷锛岄偅涔堝彲浠ョ洿鎺ヤ娇鐢↖dType.AUTO鍋氳嚜澧?/p>

1銆佹暟鎹簱瀛楁璁剧疆鑷

2銆佸疄浣撶被娣诲姞娉ㄨВ锛欯TableId(type = IdType.AUTO)

 @TableId(type = IdType.AUTO) // 杩欎釜闇€瑕侀厤鍚堟暟鎹簱璁剧疆鑷鏉ヤ娇鐢?
 private Integer id;

3.3.2銆両NPUT鐨勪娇鐢?/h3>

瀵逛簬Postgresql鏁版嵁搴擄紝骞朵笉鏀寔鐩存帴璁剧疆瀛楁鑷锛岄渶瑕侀澶栬缃畇equence鏉ュ畬鎴愶紝閭i渶瑕佷娇鐢?code>type = IdType.INPUT鏉ヨ缃?/p>

  • 1銆侀厤缃被涓紪鍐欎富閿瓥鐣?/strong>

    鍐呯疆鏀寔锛?/p>

    • DB2KeyGenerator
    • H2KeyGenerator
    • KingbaseKeyGenerator
    • OracleKeyGenerator
    • PostgreKeyGenerator
     @Configuration
     public class MyBatisPlusConfig {
         /**
          * postgresql鏁版嵁搴撲富閿敓鎴愮瓥鐣?
          */
         @Bean
         public IKeyGenerator keyGenerator() {
             return new PostgreKeyGenerator();
         }
     }
    
    
  • 2銆佸疄浣撶被閰嶇疆seq

     // 绫讳笂浣跨敤@KeySequence鎸囧畾sequence銆佹暟鎹簱绫诲瀷
     @KeySequence(value = "seq_user", dbType = DbType.POSTGRE_SQL)
     public class User extends Model<User> {
         // 瀛楁涓婁娇鐢ˊTableId锛屾寚瀹氭暟鎹簱瀛楁鍚嶃€佷富閿瓥鐣ョ被鍨?
         @TableId(value = "user_id", type = IdType.INPUT)
         private Integer userId;
     }
    
    

鍥涖€佹嫇灞?/h2>

4.1銆佹彃浠?/h2>

缂栧啓閰嶇疆鏂囦欢锛屽湪閰嶇疆鏂囦欢閲岄泦鎴愭彃浠?/p>

 @MapperScan("") // 鍙互鎶婂惎鍔ㄧ被涓婄殑dao鐨勬枃浠剁洰褰曟斁鍒拌繖閲?
 @EnableTransactionManagement
 @Configuration
 public class MyBatisPlusConfig {
     /**
      * 鎻掍欢閰嶇疆
      */
 }

4.1.1銆佸垎椤垫彃浠?/h3>
  • 娉ㄥ唽鎻掍欢

     @MapperScan("") // 鍙互鎶婂惎鍔ㄧ被涓婄殑dao鐨勬枃浠剁洰褰曟斁鍒拌繖閲?
     @EnableTransactionManagement
     @Configuration
     public class MyBatisPlusConfig {
    
        /**
          * MybatisPlus鍒嗛〉鎻掍欢閰嶇疆
          */
         @Bean
         public MybatisPlusInterceptor mybatisPlusInterceptor(){
             MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
             PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.POSTGRE_SQL);
             mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
             return mybatisPlusInterceptor;
         }
     }
    
    
  • 浣跨敤鎻掍欢

    銆愬唴缃殑mapper鏂规硶銆?/p>

    Mybatis-plus鐨勫唴缃柟娉曪紝杩涜鍒嗛〉锛屽彲浠ョ洿鎺ヤ娇鐢紙鏂规硶绗竴涓弬鏁颁紶鍏age瀵硅薄锛?/p>

     Page<User> page = new Page<>(1, 5);
     userMapper.selectPage(page, null);
     return page;
    
    

    銆愯嚜瀹氫箟鐨刴apper鏂规硶銆?/p>

    瀵逛簬鑷畾涔夌殑mapper鏂规硶鎯宠鍒嗛〉锛岄渶瑕佸湪mapper灞傜殑鏂规硶涓澶栧鍔爌age瀵硅薄鍙傛暟

     IPage<UserVo> selectPageVo(IPage<?> page, Integer state);
     // or (class MyPage extends Ipage<UserVo>{ private Integer state; })
     MyPage selectPageVo(MyPage page);
     // or
     List<UserVo> selectPageVo(IPage<UserVo> page, Integer state);
    
    
     <select id="selectPageVo" resultType="xxx.xxx.xxx.UserVo">
         SELECT id,name FROM user WHERE state=#{state}
     </select>
    
    

4.1.2銆佷箰瑙傞攣鎻掍欢

銆愬満鏅€?/p>

褰撹鏇存柊涓€鏉¤褰曠殑鏃跺€欙紝鍦ㄦ洿鏂扮殑杩囩▼涓紝甯屾湜杩欐潯璁板綍娌℃湁琚埆浜烘洿鏂?/p>

銆愬師鐞嗐€?/p>

涔愯閿佸疄鐜版柟寮忥細

  • 鍙栧嚭璁板綍鏃讹紝鑾峰彇褰撳墠 version
  • 鏇存柊鏃讹紝甯︿笂杩欎釜 version
  • 鎵ц鏇存柊鏃讹紝 set version = newVersion where version = oldVersion
  • 濡傛灉 version 涓嶅锛屽氨鏇存柊澶辫触
  • 娉ㄥ唽鎻掍欢

     @MapperScan("") // 鍙互鎶婂惎鍔ㄧ被涓婄殑dao鐨勬枃浠剁洰褰曟斁鍒拌繖閲?
     @EnableTransactionManagement
     @Configuration
     public class MyBatisPlusConfig {
         /**
          * 涔愯閿佹彃浠?
          */
         @Bean
         public MybatisPlusInterceptor mybatisPlusInterceptor() {
             MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
             mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
             return mybatisPlusInterceptor;
         }
     }
    
    
  • 浣跨敤鎻掍欢

    1銆佹暟鎹簱瀹氫箟瀛楁

    2銆佸湪瀛楁涓婂姞@Version娉ㄨВ

     @Version
     private Integer version;
    
    

4.1.3銆佹€ц兘鍒嗘瀽鎻掍欢

瀵箂ql鐨勬牸寮忓寲杈撳嚭銆乻ql鎵ц鏃堕棿銆佸綋瓒呰繃璁剧疆鐨勬椂闂村垯鎶ラ敊

銆愬缓璁€戯細閰嶇疆浠呭湪dev鍜宼est灏辩幆澧冧笅鐢熸晥

  • 娉ㄥ唽鎻掍欢

     @MapperScan("") // 鍙互鎶婂惎鍔ㄧ被涓婄殑dao鐨勬枃浠剁洰褰曟斁鍒拌繖閲?
     @EnableTransactionManagement
     @Configuration
     public class MyBatisPlusConfig {
         /**
          * 鎬ц兘鍒嗘瀽鎻掍欢
          */
         @Bean
         @Profile({"dev", "test"}) // 閰嶇疆浠呭湪dev鍜宼est灏辩幆澧冧笅鐢熸晥
         public PerformanceInterceptor performanceInterceptor() {
           PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
           // 璁剧疆sql鏈€澶ф墽琛屾椂闂达紙姣锛夛紝瓒呰繃鍒欎笉鎵ц
           performanceInterceptor.setMaxTime(500);
           // 璁剧疆瀵硅緭鍑虹殑sql鏍煎紡鍖?
           performanceInterceptor.setFormat(true);
           return performanceInterceptor;
         }
     }
    
    
  • 浣跨敤鎻掍欢

    鐩存帴鍦ㄦ帶鍒跺彴鐪嬪嵆鍙?/p>

4.2銆佷唬鐮佺敓鎴愬櫒

mybatis-plus鏀寔閫氳繃浠g爜锛屼竴閿敓鎴愶細鐩綍銆佸璞℃枃浠躲€佷唬鐮?/p>

  • 浣跨敤绀轰緥

     public class MyFastAutoGenerator {
     
         /**
          * 缁濆椤圭洰鏍硅矾寰?
          */
         private static final String OUT_DIR = "";
         /**
          * 椤圭洰鍖呰矾寰?
          */
         private static final String PROJECT_DIR = "";
         /**
          * 妯″潡鍚?
          */
         private static final String MODULE_NAME = "";
         /**
          * 鏁版嵁搴撻厤缃?
          */
         private static final String URL = "";
         private static final String USERNAME = "";
         private static final String PASSWORD = "";
     
         /**
          * 闇€瑕佺敓鎴愮殑琛ㄥ悕绉?鍙互濉涓?
          */
         private static final String[] GENERATE_TABLES = {"user"};
     
     
         public static void main(String[] args) {
             FastAutoGenerator.create(URL, USERNAME, PASSWORD)
                     // 鍏ㄥ眬閰嶇疆
                     .globalConfig(builder -> {
                         builder.outputDir(OUT_DIR)
                                 // 閰嶇疆鐢熸垚鏂囦欢涓殑author
                                 .author("")
                                 // 娉ㄩ噴鏃ユ湡鐨勬牸寮?
                                 .commentDate("yyyy-MM-dd HH:mm:ss")
                                 .build();
                     })
                     // 鍖呴厤缃?
                     .packageConfig(builder -> {
                         builder.parent(PROJECT_DIR)
                                 .moduleName(MODULE_NAME)
                                 .controller("controller")
                                 .service("service")
                                 .serviceImpl("service.impl")
                                 .mapper("dao")
                                 .xml("dao.xml")
                                 .entity("model");
                     })
                     // Entity绛栫暐閰嶇疆
                     .strategyConfig(builder -> {
                         builder.addInclude(GENERATE_TABLES)
                                 // 璺宠繃瑙嗗浘鐨勭敓鎴?
                                 .enableSkipView()
                                 // 鍘婚櫎鍓嶇紑
                                 .addTablePrefix("t_")
                                 .entityBuilder()
                                 // 椹煎嘲
                                 .naming(NamingStrategy.underline_to_camel)
                                 .build();
                     })
                     // Service绛栫暐閰嶇疆
                     .strategyConfig(builder -> {
                         builder.serviceBuilder()
                                 .formatServiceFileName("%sService")
                                 .build();
                     })
                     // Mapper绛栫暐閰嶇疆
                     .strategyConfig(builder -> {
                         builder.mapperBuilder()
                                 .formatMapperFileName("%sDao")
                                 .build();
                     })
                     // 鍙互浣跨敤Freemarker寮曟搸妯℃澘锛岄粯璁ょ殑鏄疺elocity寮曟搸妯℃澘
                     .templateEngine(new VelocityTemplateEngine())
                     .execute();
         }
     }
    
    
  • 鏁堟灉灞曠ず

    你还没用过Mybatis-Plus?丝般顺滑,快速上手!,第3张


https://www.xamrdz.com/backend/3dy1936077.html

相关文章: