Spring Boot 통합 MyBatis 방법

봄 부츠 통합 MyBatis
MyBatis 를 통합 하기 전에,우 리 는 먼저 druid 데이터 원본 을 설정 합 니 다.
스프링 부츠 통합 druiddruid여러 설정 옵션 이 있 습 니 다.Spring Boot 의 설정 파일 을 사용 하면 편리 하 게 설정 할 수 있 습 니 다druid.application.yml프로필 에 쓰기:

spring:
  datasource:
    name: test
    url: jdbc:mysql://192.168.16.137:3306/test
    username: root
    password:
    #   druid   
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
여 기 는type: com.alibaba.druid.pool.DruidDataSource설정 을 통 해 설정 하면 됩 니 다!
봄 부츠 통합 MyBatis
Spring Boot 통합 MyBatis 는 두 가지 방식 이 있 습 니 다.간단 한 방법 은 MyBatis 가 공식 적 으로 제공 하 는 것 입 니 다.
mybatis-spring-boot-starter
또 다른 방식 은 여전히 유사 한mybatis-spring설정 방식 을 사용 하 는 것 이다.이런 방식 은 스스로 코드 를 써 야 하지만 MyBatis 의 각종 설정 을 편리 하 게 제어 할 수 있다.
1.my batis-spering-boot-starter 방식pom.xml에 의존 도 를 추가 합 니 다:

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.0.0</version>
</dependency>
mybatis-spring-boot-starter의존 나 무 는 다음 과 같다.
  • 그 중에서 my batis 가 사용 하 는 3.3.0 버 전 은3.3.0속성 을 통 해 기본 버 전 을 수정 할 수 있 습 니 다.
  • mybatis-spring 사용 버 전 1.2.3,1.2.3을 통 해 기본 버 전 을 수정 할 수 있 습 니 다.
  • application.yml 에 설정 추가:
    
    mybatis: 
     mapperLocations: classpath:mapper/*.xml
     typeAliasesPackage: tk.mapper.model 
    위 에서 흔히 볼 수 있 는 두 가지 설정 외 에 도:
  • mybatis.config:mybatis-config.xml 프로필 의 경로
  • mybatis.typeHandlers Package:typeHandlers 의 가방 스 캔
  • mybatis.checkConfigLocation:설정 파일 이 존재 하 는 지 확인
  • my batis.executor Type:실행 모드(SIMPLE,REUSE,BATCH)를 설정 하고 기본 값 은 SIMPLE
  • 입 니 다.
    2.my batis-spering 방식
    이런 방식 은 일반적인 용법 과 비교적 가깝다.mybatis 의존 과 mybatis-spring 의존 을 추가 해 야 합 니 다.
    그리고 MyBatisConfig 설정 클래스 를 만 듭 니 다:
    
    /**
     * MyBatis    
     */
    @Configuration
    @EnableTransactionManagement
    public class MyBatisConfig implements TransactionManagementConfigurer {
      @Autowired
      DataSource dataSource;
      @Bean(name = "sqlSessionFactory")
      public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
        //    
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        //    
        bean.setPlugins(new Interceptor[]{pageHelper});
        //  XML  
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
          bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
          return bean.getObject();
        } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException(e);
        }
      }
      @Bean
      public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
      }
      @Bean
      @Override
      public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
      }
    }
    위의 코드 는 하나SqlSessionFactory와 하나SqlSessionTemplate를 만 들 었 습 니 다.주석 업 무 를 지원 하기 위해@EnableTransactionManagement주 해 를 추가 하고 하나PlatformTransactionManagerBean를 되 돌 렸 습 니 다.
    또한 이 설정 에MapperScannerConfigurer이 없 음 을 알 아야 합 니 다.MyBatis 의 Mapper 인 터 페 이 스 를 스 캔 하려 면 이 종 류 를 설정 해 야 합 니 다.이 설정 은 하나의 클래스 에 따로 넣 어야 합 니 다.
    
    /**
     * MyBatis    
     */
    @Configuration
    //TODO   ,  MapperScannerConfigurer      ,          
    @AutoConfigureAfter(MyBatisConfig.class)
    public class MyBatisMapperScannerConfig {
      @Bean
      public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper");
        return mapperScannerConfigurer;
      }
    }
    이 설정 은 반드시 주의해 야 합 니 다@AutoConfigureAfter(MyBatisConfig.class).이 설정 이 있어 야 합 니 다.그렇지 않 으 면 이상 이 있 을 수 있 습 니 다.원인 은 바로 이런 종류의 집행 이 비교적 이 르 기 때문이다.sqlSessionFactory아직 존재 하지 않 기 때문에 후속 집행 이 잘못 되 었 다.
    위 설정 을 완료 하면 MyBatis 를 사용 할 수 있 습 니 다.
    페이지 플러그 인과 유 니 버 설 Mapper 통합 에 대하 여
    페이지 플러그 인 은 플러그 인의 예 로 위의 코드 에 있 습 니 다.
    유 니 버 설 Mapper 설정 은 실제 설정MapperScannerConfigurer일 때 사용tk.mybatis.spring.mapper.MapperScannerConfigurer하면 되 며,속성 설정Properties을 사용 하면 됩 니 다.
    Spring Boot 통합 MyBatis 의 기본 프로젝트
    저 는 github 에 두 번 째 방식 의 통합 프로젝트 를 올 렸 고 페이지 플러그 인과 유 니 버 설 Mapper 를 통합 시 켰 습 니 다.프로젝트 는 간단 한 설정 과 조작 을 포함 하여 참고 로 만 들 었 습 니 다.
    프로젝트 주소:https://github.com/abel533/MyBatis-Spring-Boot
    페이지 플러그 인과 유 니 버 설 Mapper 에 관 한 정 보 는 위 주 소 를 통 해 찾 을 수 있 습 니 다.
    총결산
    이상 은 이 글 의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가 치 를 가지 기 를 바 랍 니 다.여러분 의 저희 에 대한 지지 에 감 사 드 립 니 다.더 많은 내용 을 알 고 싶다 면 아래 링크 를 보 세 요.

    좋은 웹페이지 즐겨찾기