SpringBoot 통합 MybatisPlus 의 간단 한 튜 토리 얼 구현(간단 한 통합)

7892 단어 SpringBootMybatisPlus
최근 에 spring boot 를 연구 하 는 김 에 데이터 베 이 스 를 연결 하 는 지식 도 볼 수 있 습 니 다.그래서 유 니 버 설 Mapper 와 Mybatis Plus 라 는 두 가지 네트워크 에서 비교적 핫 한 my batis 개발 을 간소화 하 는 우수한 소프트웨어 를 발견 한 후에.다 해 보고 싶 어 요.어떤 게 잘 어 울 리 는 지.
먼저 springboot 프로젝트 를 만 들 고 제 이전 글 Spring Boot 의 간단 한 튜 토리 얼(1)Spring Boot 프로젝트 의 생 성 을 참고 할 수 있 습 니 다.
springboot 을 만 든 후 my batis 와 my batis-plus 를 통합 해 야 합 니 다.
pom.xml 파일 을 열 고 최신 my batis 와 관련 된 가방 을 모두 참조 합 니 다.

    <!--   mysql    -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <!--   lombok    -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <!--   mybatis-plus   -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.1.1</version>
    </dependency>
    <!--   mybatis-plus         -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-generator</artifactId>
      <version>3.1.1</version>
    </dependency>
    <!--          -->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.28</version>
    </dependency>
application.yml 에 대한 설정 이 필요 합 니 다.

  #   
  server:
   port: 8088
  #        
  spring:
   datasource:
    url: jdbc:mysql://localhost:3306/*** #        
    username: root
    password: 123456
  mybatis:
   #       
   configuration:
    map-underscore-to-camel-case: true
  mybatis-plus:
   # xml  
   mapper-locations: classpath:mapper/*Mapper.xml
   #     ,  package         
   type-aliases-package: ***  #        
   configuration:
    #          sql    ,            
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
모듈 을 자동 으로 생 성 하 는 방법 은 해당 위치 에 자신의 가방 이름 을 추가 하면 해당 하 는 Entity,Mapper,Mapper XML,Service,Controller 등 각 모듈 의 코드 를 생 성 할 수 있다.

public class CodeGenerator {

  /**
   * <p>
   *        
   * </p>
   */
  public static String scanner(String tip) {
    Scanner scanner = new Scanner(System.in);
    StringBuilder help = new StringBuilder();
    help.append("   " + tip + ":");
    System.out.println(help.toString());
    if (scanner.hasNext()) {
      String ipt = scanner.next();
      if (StringUtils.isNotEmpty(ipt)) {
        return ipt;
      }
    }
    throw new MybatisPlusException("      " + tip + "!");
  }

  public static void main(String[] args) {
    //      
    AutoGenerator mpg = new AutoGenerator();
    //     
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("jobob");
    gc.setOpen(false);
    // gc.setSwagger2(true);      Swagger2   
    mpg.setGlobalConfig(gc);

    //      
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/***?useUnicode=true&useSSL=false&characterEncoding=utf8");
    // dsc.setSchemaName("public");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("***");
    mpg.setDataSource(dsc);

    //    
    PackageConfig pc = new PackageConfig();
    //          ,       。
//    pc.setModuleName(scanner("   "));
    pc.setParent("com.zhouxiaoxi.www");
    mpg.setPackageInfo(pc);

    //      
    InjectionConfig cfg = new InjectionConfig() {
      @Override
      public void initMap() {
        // to do nothing
      }
    };

    //         freemarker
    String templatePath = "/templates/mapper.xml.ftl";
    //         velocity
//     String templatePath = "/templates/mapper.xml.vm";

    //        
    List<FileOutConfig> focList = new ArrayList<>();
    //            
    focList.add(new FileOutConfig(templatePath) {
      @Override
      public String outputFile(TableInfo tableInfo) {
        //          ,     Entity       、     xml           !!
        return projectPath + "/src/main/resources/mapper/"
//            + + pc.getModuleName() +           ,          
            + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
      }
    });
    /*
    cfg.setFileCreate(new IFileCreate() {
      @Override
      public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
        //               
        checkDir("           ");
        return false;
      }
    });
    */
    cfg.setFileOutConfigList(focList);
    mpg.setCfg(cfg);

    //     
    TemplateConfig templateConfig = new TemplateConfig();

    //          
    //         ,      .ftl/.vm,               
    // templateConfig.setEntity("templates/entity2.java");
    // templateConfig.setService();
    // templateConfig.setController();

    templateConfig.setXml(null);
    mpg.setTemplate(templateConfig);

    //     
    StrategyConfig strategy = new StrategyConfig();
    //              
    strategy.setNaming(NamingStrategy.underline_to_camel);
    //                ,       naming   
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    //      Entity   ,   
//    strategy.setSuperEntityClass("***");
    strategy.setEntityLombokModel(true);
    strategy.setRestControllerStyle(true);
    //      Controller   ,   
//    strategy.setSuperControllerClass("***");
    strategy.setInclude(scanner("  ,        ").split(","));
    //      Entity ,    (     )
//    strategy.setSuperEntityColumns("id");
    //      
    strategy.setControllerMappingHyphenStyle(true);
    //   
//    strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
  }

}
생 성 된 contrller 에 대응 하 는 방법 을 추가 하여 시작 하면 정상적으로 접근 할 수 있 습 니 다.

물론 Spring Boot 시작 클래스 에@MapperScan 주 해 를 추가 하고 Mapper 폴 더 를 스 캔 해 야 합 니 다.

@SpringBootApplication
@MapperScan("***.*.mapper") //    mapper     
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(QuickStartApplication.class, args);
  }

}
 이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기