Mybatis-Plus 의 사용 에 대한 상세 한 설명

21267 단어 Mybatis-Plus쓰다
특성
  • 무 침입:강화 만 하고 변 화 를 하지 않 으 며 도입 은 기 존 공사 에 영향 을 주지 않 습 니 다.예 를 들 어 실크 처럼 미 끄 러 운
  • .
  • 손실 이 적 음:시작 하면 자동 으로 기본 CURD 를 주입 하고 성능 은 기본적으로 손실 이 없 으 며 대상 을 대상 으로 직접 조작 합 니 다.BaseMapper
  • 강력 한 CRUD 작업:유 니 버 설 Mapper,유 니 버 설 서 비 스 를 내장 하고 소량의 설정 만으로 표 의 대부분
  • 을 실현 할 수 있 습 니 다.
  • CRUD 조작,더욱 강력 한 조건 구조 기,각종 사용 수 요 를 만족 시 킵 니 다.앞으로 간단 한 CRUD 조작 은 스스로 작성 할 필요 가 없습니다!
  • Lambda 형식 호출 지원:Lambda 표현 식 을 통 해 각종 조회 조건 을 편리 하 게 작성 할 수 있 습 니 다.필드 오류
  • 을 걱정 하지 않 아 도 됩 니 다.
  • 메 인 키 자동 생 성 지원:4 가지 메 인 키 정책(분포 식 유일한 ID 생 성기-Sequence 포함)을 지원 하고 자 유 롭 게 설정 할 수 있 으 며 메 인 키 문 제 를 완벽 하 게 해결 할 수 있 습 니 다
  • 지원 ActiveRecord 모드:ActiveRecord 형식 호출 을 지원 합 니 다.실체 류 는 모델 류 만 계승 하면 강력 한 CRUD
  • 을 진행 할 수 있 습 니 다.
  • 조작
  • 사용자 정의 전역 유 니 버 설 작업 지원:전역 유 니 버 설 방법 주입 지원(Write once,use anywhere)
  • 내장 코드 생 성기:코드 나 Maven 플러그 인 을 사용 하면 Mapper,Model,Service,Controller
  • 을 신속하게 생 성 할 수 있 습 니 다.
  • 층 코드,템 플 릿 엔진 지원,초 다 중 사용자 정의 설정 등 사용(자동 으로 코드 생 성)
  • 내 장 된 페이지 플러그 인:MyBatis 물리 페이지 를 바탕 으로 개발 자 는 구체 적 인 조작 에 관심 을 가 질 필요 가 없습니다.플러그 인 을 설정 한 후에 페이지 를 쓰 는 것 은 일반 List 조회
  • 과 같 습 니 다.
  • 페이지 플러그 인 은 다양한 데이터 베 이 스 를 지원 합 니 다.MySQL,MariaDB,Oracle,DB2,H2,HSQL,SQLite,
  • 을 지원 합 니 다.
  • Postgre,SQLServer 등 다양한 데이터베이스
  • 내장 성능 분석 플러그 인:Sql 문 구 를 출력 할 수 있 고 실행 시간 입 니 다.테스트 를 개발 할 때 이 기능 을 사용 하 는 것 을 권장 합 니 다.느 린 조회
  • 을 신속하게 찾 을 수 있 습 니 다.
  • 내 장 된 전역 차단 플러그 인:전체 표 delete,update 작업 스마트 분석 차단 을 제공 하고 차단 규칙 을 사용자 정의 하여 오 작 동 을 예방 할 수 있 습 니 다.
  • 2.사용 절차
    1.데이터베이스 mybatis 만 들 기플러스,생 성 표
    
    DROP TABLE IF EXISTS user;
    CREATE TABLE user
    (
    id BIGINT(20) NOT NULL COMMENT '  ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '  ',
    age INT(11) NULL DEFAULT NULL COMMENT '  ',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '  ',
    PRIMARY KEY (id)
    );
    INSERT INTO user (id, name, age, email) VALUES
    (1, 'Jone', 18, '[email protected]'),
    (2, 'Jack', 20, '[email protected]'),
    (3, 'Tom', 28, '[email protected]'),
    (4, 'Sandy', 21, '[email protected]'),
    (5, 'Billie', 24, '[email protected]');
    --      ,version(   )、deleted(    )、gmt_create、gmt_modified
    2、SpringBoot 프로젝트 를 만 듭 니 다!
    3.가 져 오기 의존
    
    <!--       -->
    <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- lombok -->
    <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
    </dependency>
    <!-- mybatis-plus -->
    <!-- mybatis-plus      ,     ! -->
    <dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-boot-starter</artifactId>
     <version>3.0.5</version>
    </dependency>
    
    4.설정
    
    # mysql 5      com.mysql.jdbc.Driver
    # mysql 8     com.mysql.cj.jdbc.Driver、         
    serverTimezone=GMT%2B8
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?
    useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
    5.실체 류 구축
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
     private Long id;
     private String name;
     private Integer age;
     private String email;
    }
    
    6.mapper 인터페이스
    
    //     Mapper         BaseMapper
    @Repository //      
    public interface UserMapper extends BaseMapper<User> {
     //    CRUD          
     //                 !
    }
    
    7.입구 류 스 캔 dao
    주 시작 클래스 에서 mapper 패키지 의 모든 인 터 페 이 스 를 검색 합 니 다.
    
    @MapperScan("com.yn.mapper")
    
    설정 로그
    우리 의 모든 sql 은 현재 보이 지 않 습 니 다.우 리 는 그것 이 어떻게 실행 되 는 지 알 고 싶 습 니 다.그래서 우 리 는 로 그 를 봐 야 합 니 다!
    
    #     
    mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    
    在这里插入图片描述
    로 그 를 설정 한 후,다음 학습 은 자동 으로 생 성 되 는 SQL 에 주의해 야 합 니 다.MyBatis-Plus 를 좋아 하 게 될 것 입 니 다!
    4.CRUD 확장
    1.삽입 작업
    
    @Autowired
     private UserMapper userMapper;
    
     @Test
     public void testInsert() {
      User user = new User();
      user.setName("  ");
      user.setAge(23);
      user.setEmail("163.com");
    
      int result = userMapper.insert(user);//       id
      System.out.println(result);//       
      System.out.println(user);//   id     
     }
    
    在这里插入图片描述
    2.메 인 키 생 성 정책
    실체 클래스 필드 에서@TableId(type=IdType.xxx),모두 6 가지 메 인 키 생 성 정책 이 있 습 니 다.
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
    /*
     @TableId(type = IdType.AUTO)  // 1.   id     :              !
     @TableId(type = IdType.NONE)  // 2.     
     @TableId(type = IdType.INPUT)  // 3.    
     @TableId(type = IdType.ID_WORKER) // 4.       id
     @TableId(type = IdType.UUID)   // 5.    id uuid
     @TableId(type = IdType.ID_WORKER_STR) // 6.ID_WORKER       
    */
     private Long id;
     private String name;
     private Integer age;
     private String email;
    }
    
    3.업데이트 작업
    
     @Test
     public void testUpdate() {
      User user = new User();
      user.setId(6L);
      user.setName("  ");
      user.setAge(29);
      user.setEmail("qq.com");
    
      int result = userMapper.updateById(user);
     }
    
    在这里插入图片描述
    4.자동 충전
    창설 시간,수정 시간!이 조작 들 은 한 번 에 모두 자동화 로 완성 되 었 으 니,우 리 는 수 동 으로 업데이트 하 는 것 을 원 하지 않 는 다!
    알 리 바 바 개발 매 뉴 얼:모든 데이터베이스 시트:gmtcreate、gmt_modified 는 거의 모든 시 계 를 설정 해 야 합 니 다!그리고 자동화 가 필요 해!
    1.방식 1:데이터베이스 단계(작업 중 데이터 베 이 스 를 수정 할 수 없습니다)
    표 에 필드 추가 createtime, update_time,
    실체 클래스 동기 화
    
    private Date createTime;
    private Date updateTime;
    
    다음은 조작 후의 변화 이다.
    在这里插入图片描述
    2.방식 2:코드 레벨
    1.데이터베이스 의 기본 값 삭제,업데이트 작업!
    在这里插入图片描述
    2.실체 필드 속성 에 주석 을 추가 해 야 합 니 다.
    
    //         
    @TableField(fill = FieldFill.INSERT)//       
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)//           
    private Date updateTime
    
    3.이 주 해 를 처리 하기 위해 프로 세 서 를 작성 하면 됩 니 다!
    
    @Slf4j
    @Component//  spring  
    public class MuMetaObjecHandler implements MetaObjectHandler {
     //         
     @Override
     public void insertFill(MetaObject metaObject) {
     log.info("start insert fill.....");
     // setFieldValByName(String    , Object      , MetaObject meateObject);
     this.setFieldValByName("createTime",new Date(),metaObject);
     this.setFieldValByName("updateTime",new Date(),metaObject);
     }
    
     //         
     @Override
     public void updateFill(MetaObject metaObject) {
      log.info("start update fill.....");
      this.setFieldValByName("updateTime",new Date(),metaObject);
     }
    }
    
    4,테스트 삽입,업데이트 후 관찰 시간!
    在这里插入图片描述
    5.낙 관 자물쇠
    낙관 자물쇠:옛 이름 의 사 의 는 매우 낙관적 입 니 다.그것 은 항상 문제 가 발생 하지 않 을 것 이 라 고 생각 합 니 다.무엇 을 하 든 자 물 쇠 를 채 우지 않 습 니 다!문제 가 발생 하면 값 테스트 를 다시 업데이트 하고 모든 기록 에 version 을 추가 합 니 다.
    비관 자물쇠:옛 이름 의 사 의 는 매우 비관 적 입 니 다.항상 문제 가 생 긴 다 고 생각 합 니 다.무엇 을 하 든 자 물 쇠 를 채 웁 니 다!다시 조작 해!
    낙관적 잠 금 실현 방식:
  • 추출 기록 시 현재 version
  • 가 져 오기
  • 업데이트 시 이 version
  • 을 가 져 가세 요.
  • 업데이트 실행 시 set version=newVersion where version=oldVersion
  • version 이 틀 리 면 업데이트 에 실패 합 니 다.
  • 
       :1、   ,      version = 1
    -- A   
    update user set name = "kuangshen", version = version + 1
    where id = 2 and version = 1
    
    -- B       ,     version = 2,    A     !
    update user set name = "kuangshen", version = version + 1
    where id = 2 and version = 1
    
    MP 의 낙관적 잠 금 플러그 인 테스트
    1,데이터베이스 에 version 필드 추가!
    在这里插入图片描述
    2.실체 클래스 에 대응 하 는 필드
    
    @Version //   Version  
    private Integer version;
    
    3.구성 요소 등록
    
    //     mapper    
    @MapperScan("com.yn.mapper")
    @EnableTransactionManagement
    @Configuration //    
    public class MyBatisPlusConfig {
     //        
     @Bean
     public OptimisticLockerInterceptor optimisticLockerInterceptor() {
      return new OptimisticLockerInterceptor();
     }
    }
    
    3.테스트
    
     //        !
     @Test
     public void testOptimisticLocker() {
      // 1、      
      User user = userMapper.selectById(1L);
      // 2、      
      user.setName("kuangshen");
      user.setEmail("[email protected]");
      // 3、      
      userMapper.updateById(user);
     }
    
     //        !    
     @Test
     public void testOptimisticLocker2() {
      //    1
      User user = userMapper.selectById(1L);
      user.setName("kuangshen111");
      user.setEmail("[email protected]");
      //                
      User user2 = userMapper.selectById(1L);
      user2.setName("kuangshen222");
      user2.setEmail("[email protected]");
      userMapper.updateById(user2);
    
      //           !
      userMapper.updateById(user); //                  !
     }
    
    在这里插入图片描述
    6.조회 조작
    
     //     
     @Test
     public void testSelectById() {
      User user = userMapper.selectById(1L);
      System.out.println(user);
     }
    
     //       !
     @Test
     public void testSelectByBatchId() {
      List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
      users.forEach(System.out::println);
     }
    
     //          map  
     @Test
     public void testSelectByBatchIds() {
      HashMap<String, Object> map = new HashMap<>();
      //       
      map.put("name", "   Java");
      map.put("age", 3);
      List<User> users = userMapper.selectByMap(map);
      users.forEach(System.out::println);
     }
    
    7.페이지 별 조회
    1.차단기 구성 요소 설정
    
    //     mapper    
    @MapperScan("com.yn.mapper")
    @EnableTransactionManagement
    @Configuration //    
    public class MyBatisPlusConfig {
     //        
     @Bean
     public OptimisticLockerInterceptor optimisticLockerInterceptor() {
      return new OptimisticLockerInterceptor();
     }
    
     //    
     @Bean
     public PaginationInterceptor paginationInterceptor() {
      return new PaginationInterceptor();
     }
    }
    
    2.페이지 대상 을 직접 사용 하면
    
     //       
     @Test
     public void testPage() {
      //    :   
      //    :    
      //          ,             !
      Page<User> page = new Page<>(2, 3);
      userMapper.selectPage(page, null);
      page.getRecords().forEach(System.out::println);
      System.out.println(page.getTotal());
     }
    
    8.삭제 작업
    
    //     
     @Test
     public void testDeleteById() {
      userMapper.deleteById(1240620674645544965L);
     }
    
     //   id    
     @Test
     public void testDeleteBatchId() {
      userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L, 1240620674645544962L));
     }
    
     //   map  
     @Test
     public void testDeleteMap() {
      HashMap<String, Object> map = new HashMap<>();
      map.put("name", "   Java");
      userMapper.deleteByMap(map);
     }
    
    9.논리 삭제
    물리 삭제:데이터베이스 에서 직접 제거
    논리 삭제:데이터베이스 에서 제거 되 지 않 고 변 수 를 통 해 그 를 무효 화 합 니 다!deleted = 0 => deleted = 1
    관리 자 는 삭 제 된 기록 을 볼 수 있 습 니 다!데이터 손실 방지,휴지통 과 유사!
    논리 삭제 단계:
    1.데이터 시트 에 deleted 필드 추가
    在这里插入图片描述
    2,실체 클래스 중 속성 증가
    
     @TableLogic //    
     private Integer deleted;
    
    3、배치!
    
     //       !
     @Bean
     public ISqlInjector sqlInjector() {
      return new LogicSqlInjector();
     }
    
    
    #       
    mybatis-plus.global-config.db-config.logic-delete-value=1
    mybatis-plus.global-config.db-config.logic-not-delete-value=0
    
    3、보기!
    在这里插入图片描述
    在这里插入图片描述
    10.성능 분석 플러그 인
    우 리 는 평소의 개발 에서 느 린 sql 을 만 날 수 있다.
    역할:성능 분석 차단기,모든 SQL 문 구 를 출력 하고 실행 시간 에 사용
    MP 도 성능 분석 플러그 인 을 제공 합 니 다.이 시간 을 초과 하면 실행 을 중단 합 니 다!
    1.플러그 인 가 져 오기
    
    /**
      * * SQL      
      * 
      */
     @Bean
     @Profile({"dev", "test"})//    dev test     ,       
     public PerformanceInterceptor performanceInterceptor() {
      PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
      performanceInterceptor.setMaxTime(100); // ms  sql       ,         
      performanceInterceptor.setFormat(true); //        
      return performanceInterceptor;
     }
    
    SpringBoot 에서 dev 또는 test 환경 으로 환경 을 설정 해 야 한 다 는 것 을 기억 하 세 요!
    
    #      
    spring.profiles.active=dev
    
    2,테스트 사용!
    
     @Test
     void contextLoads() {
      //       Wrapper ,     ,        null
      //       
      List<User> users = userMapper.selectList(null);
      users.forEach(System.out::println);
     }
    
    在这里插入图片描述
    11.조건 구조 기
    우 리 는 복잡 한 sql 을 쓰 면 그것 으로 대체 할 수 있 습 니 다!
    
    @SpringBootTest
    public class WrapperTest {
    
     @Autowired
     private UserMapper userMapper;
    
     //1、   ,       SQL    
     @Test
     void test1() {
      //   name      ,          ,      12
      QueryWrapper<User> wrapper = new QueryWrapper<>();
      wrapper
        .isNotNull("name")
        .isNotNull("email")
        .ge("age", 12);
      userMapper.selectList(wrapper).forEach(System.out::println); //         map    
     }
    
     //2、   
     @Test
     void test2() {
      //        
      QueryWrapper<User> wrapper = new QueryWrapper<>();
      wrapper.eq("name", "   ");
      User user = userMapper.selectOne(wrapper); //       ,        List   Map
      System.out.println(user);
     }
    
     //3、    
     @Test
     void test3() {
      //       20 ~ 30       
      QueryWrapper<User> wrapper = new QueryWrapper<>();
      wrapper.between("age", 20, 30); //   
      Integer count = userMapper.selectCount(wrapper);//      
      System.out.println(count);
     }
    
     //4、    
     @Test
     void test4() {
      //       20 ~ 30       
      QueryWrapper<User> wrapper = new QueryWrapper<>();
      //       e      t%
      wrapper
        .notLike("name", "e")
        .likeRight("email", "t");
      List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
      maps.forEach(System.out::println);
     }
    
     //5、    
     @Test
     void test5() {
      QueryWrapper<User> wrapper = new QueryWrapper<>();
      // id         
      wrapper.inSql("id", "select id from user where id<3");
    
      List<Object> objects = userMapper.selectObjs(wrapper);
      objects.forEach(System.out::println);
     }
    
     //  
     @Test
     void test6() {
      QueryWrapper<User> wrapper = new QueryWrapper<>();
      //   id    
      wrapper.orderByDesc("id");
      List<User> users = userMapper.selectList(wrapper);
      users.forEach(System.out::println);
     }
    
    }
    
    12.코드 자동 생 성기
    AutoGenerator 는 MyBatis-Plus 의 코드 생 성기 로,AutoGenerator 를 통 해 Entity,Mapper,Mapper XML,Service,Controller 등 각 모듈 의 코드 를 빠르게 생 성하 여 개발 효율 을 극 대화 했다.
    테스트:
    
    package com.yn;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
    import com.baomidou.mybatisplus.generator.config.GlobalConfig;
    import com.baomidou.mybatisplus.generator.config.PackageConfig;
    import com.baomidou.mybatisplus.generator.config.StrategyConfig;
    import com.baomidou.mybatisplus.generator.config.po.TableFill;
    import com.baomidou.mybatisplus.generator.config.rules.DateType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import java.util.ArrayList;
    
    
    public class Code {
    
     public static void main(String[] args) {
      //                  
      AutoGenerator mpg = new AutoGenerator();
      //     
      // 1、    
      GlobalConfig gc = new GlobalConfig();
      String projectPath = System.getProperty("user.dir");//         
      gc.setOutputDir(projectPath + "/src/main/java");
      gc.setAuthor("   ");//  
      gc.setOpen(false);//         
      gc.setFileOverride(false); //          
      gc.setServiceName("%sService"); //  Service I  ,   server      
      gc.setIdType(IdType.ID_WORKER); //id    
      gc.setDateType(DateType.ONLY_DATE);//     
      gc.setSwagger2(true);//    Swagger  
      mpg.setGlobalConfig(gc);
      //2、     
      DataSourceConfig dsc = new DataSourceConfig();
      dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
      dsc.setDriverName("com.mysql.cj.jdbc.Driver");
      dsc.setUsername("root");
      dsc.setPassword("root");
      dsc.setDbType(DbType.MYSQL);
      mpg.setDataSource(dsc);
      //3、    
      PackageConfig pc = new PackageConfig();
      pc.setModuleName("blog");//     
      pc.setParent("com.yn");//      
      pc.setEntity("entity");//       
      pc.setMapper("mapper");//dao   
      pc.setService("service");//server   
      pc.setController("controller");//controller   
      mpg.setPackageInfo(pc);
      //4、    
      StrategyConfig strategy = new StrategyConfig();
      strategy.setInclude("user"); //         
      strategy.setNaming(NamingStrategy.underline_to_camel);//              
      strategy.setColumnNaming(NamingStrategy.underline_to_camel);//                
      strategy.setEntityLombokModel(true); //      lombok;
      strategy.setLogicDeleteFieldName("deleted");//    
      //       
      TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
      TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
      ArrayList<TableFill> tableFills = new ArrayList<>();
      tableFills.add(gmtCreate);
      tableFills.add(gmtModified);
      strategy.setTableFillList(tableFills);
      //    
      strategy.setVersionFieldName("version");
      strategy.setRestControllerStyle(true);//      
      strategy.setControllerMappingHyphenStyle(true); //controller     :localhost:8080/hello_id_2
      mpg.setStrategy(strategy);
    
      mpg.execute(); //  
     }
    }
    
    틀린 것 은 이 가방 을 안내 해 주 셔 도 됩 니 다.
    
     <dependency>
       <groupId>org.apache.velocity</groupId>
       <artifactId>velocity-engine-core</artifactId>
       <version>2.0</version>
      </dependency>
    
    여기에 Mybatis-Plus 의 사용 에 대한 상세 한 설명 이 있 는 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 Mybatis-Plus 의 사용 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

    좋은 웹페이지 즐겨찾기