码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot 集成MyBatis

时间:2017-07-30 18:10:48      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:分页   nes   基础配置   type   processor   data   art   cto   ota   

Spring Boot 集成MyBatis

在集成MyBatis前,我们先配置一个druid数据源。

Spring Boot 系列

  1. Spring Boot 入门

  2. Spring Boot 属性配置和使用

  3. Spring Boot 集成MyBatis

  4. Spring Boot 静态资源处理

  5. Spring Boot - 配置排序依赖技巧

  6. Spring Boot - DevTools 介绍

Spring Boot 集成druid

druid有非常多个配置选项,使用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配置就可以!

Spring Boot 集成MyBatis

Spring Boot 集成MyBatis有两种方式。一种简单的方式就是使用MyBatis官方提供的:

mybatis-spring-boot-starter

第二种方式就是仍然用相似mybatis-spring的配置方式,这样的方式须要自己写一些代码,可是能够非常方便的控制MyBatis的各项配置。

一、mybatis-spring-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依赖树例如以下:
技术分享

当中mybatis使用的3.3.0版本号,能够通过:
<mybatis.version>3.3.0</mybatis.version>属性改动默认版本号。
mybatis-spring使用版本号1.2.3,能够通过:
<mybatis-spring.version>1.2.3</mybatis-spring.version>改动默认版本号。

application.yml中添加配置:

mybatis: 
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: tk.mapper.model 

除了上面常见的两项配置。还有:

  • mybatis.config:mybatis-config.xml配置文件的路径
  • mybatis.typeHandlersPackage:扫描typeHandlers的包
  • mybatis.checkConfigLocation:检查配置文件是否存在
  • mybatis.executorType:设置运行模式(SIMPLE, REUSE, BATCH),默觉得SIMPLE

二、mybatis-spring方式

这样的方式和寻常的使用方法比較接近。

须要加入mybatis依赖和mybatis-spring依赖。

然后创建一个MyBatisConfig配置类:

/**
 * MyBatis基础配置
 *
 * @author liuzh
 * @since 2015-12-19 10:11
 */
@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扫描接口
 * 
 * @author liuzh
 * @since 2015-12-19 14:46
 */
@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的相关信息能够通过上面地址找到。

Spring Boot 集成MyBatis

标签:分页   nes   基础配置   type   processor   data   art   cto   ota   

原文地址:http://www.cnblogs.com/gavanwanggw/p/7259646.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!