my batis - plus 고급 기능 사용자 정의 통용 방법 상세 설명

머리말
MP 는 처음부터 많은 일반적인 방법 을 제공 해 왔 습 니 다. DefaultSqlInjector 라 는 클래스 에 MethodList 라 는 집합 에 포 함 된 것 은 모두 일반적인 방법 클래스 입 니 다. 사용자 정의 통용 방법 을 사용 하려 면 이 집합 에 추가 해 야 합 니 다.
/**
 * SQL      
 *
 * @author hubin
 * @since 2018-04-10
 */
public class DefaultSqlInjector extends AbstractSqlInjector {
     
 
    @Override
    public List<AbstractMethod> getMethodList() {
     
        return Stream.of(
            new Insert(),
            new Delete(),
            new DeleteByMap(),
            new DeleteById(),
            new DeleteBatchByIds(),
            new Update(),
            new UpdateById(),
            new SelectById(),
            new SelectBatchByIds(),
            new SelectByMap(),
            new SelectOne(),
            new SelectCount(),
            new SelectMaps(),
            new SelectMapsPage(),
            new SelectObjs(),
            new SelectList(),
            new SelectPage()
        ).collect(toList());
    }
}

사용자 정의 방법 구현 - 삭제 시 채 우기 예:
  • 사용자 정의 방법 을 만 드 는 클래스
  • 클래스 이름 은 DelFillUserMethod 입 니 다. 이것 은 사용자 정의 이지 만 이름 을 알 고 의 미 를 아 는 클래스 가 좋 습 니 다.
  • AbstractMethod 추상 류 를 계승 하고 AbstractMethod 는 추상 적 인 주입 방법 류 이 며 모든 통용 방법 도 이 종 류 를 계승 하 였 으 며 그 안의 방법
  • 을 편리 하 게 호출 하기 위해 서 이다.
  • inject Mapped Statement 방법 을 다시 쓰 는 것 은 inject Mapped Statement 에서 우리 가 이 방법 을 완성 하 는 구체 적 인 논리 입 니 다.
  • CustomSqlMethod 는 사용자 정의 매 거 진 클래스 입 니 다. 저 는 아래 에 붙 여 놓 았 습 니 다. 이렇게 하면 코드 를 더욱 우아 하 게 할 수 있 습 니 다. 저 는 공식 적 으로 제공 하 는 SqlMethod 를 선택 하지 않 았 습 니 다. 그때 유지 하기 가 쉽 지 않 을 까 봐 제 것 을 썼 습 니 다. 이것 은 모두 사람 을 보 는 것 입 니 다.
  • 구체 적 인 내용 은 코드 에 도 주석 이 있 습 니 다.
  • 
    /**
     * @auther: zpq
     * @date: 2020/11/9 19:55
     * @description:           
     */
    public class DelFillUserMethod extends AbstractMethod {
         
    
      @Override
      public MappedStatement injectMappedStatement(
          Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
         
    
        //       
        String userId = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getId2();
        String userName = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getName();
    
    	// set   
        String set = "set useflag = 0,deletetime = now(),operatetime = now()";
    
        if (StringUtils.isNotBlank(userId)) set += ",set deleterid = " + userId;
        if (StringUtils.isNotBlank(userName)) set += ",set deleter = " + userName;
    
        //           
        CustomSqlMethod sqlMethod = CustomSqlMethod.DEL_FILL_USER;
    
        /** *      sql */
        String sql =
            String.format(
                //     sql
                sqlMethod.getSql(),
                //   
                tableInfo.getTableName(),
                // set   
                set,
                //   (      )
                tableInfo.getKeyColumn(),
                //       
                tableInfo.getKeyProperty(),
                // and    = yes |    false     and    = no
                tableInfo.getLogicDeleteSql(true, true));
    
        //   SQL     
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
    
        //   mp       
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
      }
    }
    
  • CustomSqlMethod 매 거 진 내용
  • /**
     * @auther: zpq
     * @date: 2020/11/10 14:29
     * @description:      sql     
     */
    public enum CustomSqlMethod {
         
        /**
         *   
         */
        INSERT_ONE("insert", "      (      )", "
    INSERT INTO %s %s VALUES %s
    "
    ), /** * */ DELETE_BY_ID("deleteById", " ID ", "
    DELETE FROM %s WHERE %s=#{%s}
    "
    ), /** * */ LOGIC_DELETE_BY_ID("deleteById", " ID ", "
    UPDATE %s %s WHERE %s=#{%s} %s
    "
    ), /** * -> */ DEL_FILL_USER("delFillUser", " ", "
    UPDATE %s %s WHERE %s=#{%s} %s
    "
    ), BATCH_DEL_FILL_USER("batchDelFillUser", " ", "
    UPDATE %s %s WHERE %s IN (%s) %s
    "
    ), /** * */ SELECT_OBJS("selectObjs", " ", "%s SELECT %s FROM %s %s %s
    "
    ); private final String method; private final String desc; private final String sql; CustomSqlMethod(String method, String desc, String sql) { this.method = method; this.desc = desc; this.sql = sql; } public String getMethod() { return method; } public String getDesc() { return desc; } public String getSql() { return sql; } }
  • 주입 기 를 만 들 고 사용자 정의 방법 을 집합 에 추가 합 니 다.
  • 클래스 이름 은 CustomSqlInjector 이 고 사용자 정의
  • DefaultSqlInjector 를 계승 하고 getMethodList 를 다시 작성 합 니 다. SQL 기본 주입 기 에서 도 언급 한 바 있 습 니 다. 일반적인 방법의 집합 methodList 에 사용자 정의 방법 을 추가 해 야 합 니 다
  • .
    /**
     * @auther: zpq
     * @date: 2020/11/9 20:00
     * @description:    sql   
     *            mp     
     */
    @Component
    public class CustomSqlInjector extends DefaultSqlInjector {
         
    
      @Override
      public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
         
        //      ,        ,        ,              
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
    
        /***
         *         
         */
        methodList.add(new DelFillUserMethod());
        methodList.add(new BatchDelFillUserMethod());
    
        return methodList;
      }
    }
    
  • 마지막 단 계 는 *. dao. * Mapper 에 사용자 정의 방법 을 추가 하 는 것 입 니 다.
  •   /**
       * @Description:           
       *
       * @param: id   id
       * @auther: zpq
       * @date: 2020/11/10 11:47   
       */
      int delFillUser(Serializable id);
    
  • 사실 이상 은 완 성 된 셈 이지 만 여러 개의 Mapper 가 이 사용자 정의 통용 방법 을 사용 해 야 한다 면 그리 우아 하지 않 을 것 이다.
  • 우 리 는 통용 SuperMapper 을 만 들 고 BaseMapper 를 계승 합 니 다. 그러면 이 방법 을 사용 한 mapper 는 SuperMapper 만 계승 하면 됩 니 다. 다음 과 같 습 니 다.
  • /**
     * @auther: zpq
     * @date: 2020/11/9 20:10
     * @description:   mapper
     */
    public interface SuperMapper<T> extends BaseMapper<T> {
         
    
      /**
       * @Description:           
       *
       * @param: id   id
       * @auther: zpq
       * @date: 2020/11/10 11:47   
       */
      int delFillUser(Serializable id);
    
      /**
       * @Description:             
       *
       * @param: idList   ID  (    null    empty)
       * @auther: zpq
       * @date: 2020/11/10 3:12   
       */
      int batchDelFillUser(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
    }
    
  • 사용자 정의 대량 작업 의 일반적인 방법 을 발 견 했 을 수도 있 습 니 다. 제 가 직접 붙 여 드 리 겠 습 니 다.
  • /**
     * @auther: zpq
     * @date: 2020/11/10 14:59
     * @description:           
     */
    public class BatchDelFillUserMethod extends AbstractMethod {
         
    
      @Override
      public MappedStatement injectMappedStatement(
          Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
         
    
        //       
        String userId = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getId2();
        String userName = UserContext.getCurrent() == null ? null : UserContext.getCurrent().getName();
    
        //     sql
        String set = "set useflag = 0,deletetime = now(),operatetime = now()";
    
        if (StringUtils.isNotBlank(userId)) set += ",set deleterid = " + userId;
        if (StringUtils.isNotBlank(userName)) set += ",set deleter = " + userName;
    
        //         sql
        CustomSqlMethod sqlMethod = CustomSqlMethod.BATCH_DEL_FILL_USER;
    
        //   sql
        String sql =
            String.format(
                sqlMethod.getSql(),
                tableInfo.getTableName(),
                set,
                tableInfo.getKeyColumn(),
                // foreach in(ids)
                SqlScriptUtils.convertForeach("#{item}", COLLECTION, null, "item", COMMA),
                tableInfo.getLogicDeleteSql(true, true));
    
        //   SQL     
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
    
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
      }
    }
    

    끝 말:
    여기까지 mybatis-plus 끝 났 습 니 다. 사실은 간단 합 니 다. 다른 방법 을 쓰 는 것 도 마찬가지 입 니 다. my batis - plus 소스 코드 를 대조 해서 베 끼 면 됩 니 다. 하하 하...

    좋은 웹페이지 즐겨찾기