Spring Boot 集成MyBatis

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的相关信息能够通过上面地址找到。

时间: 2024-08-09 01:38:08

Spring Boot 集成MyBatis的相关文章

Spring Boot集成MyBatis实现通用Mapper

前言 MyBatis关于MyBatis,大部分人都很熟悉.MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录.不管是DDD(Domain Driven Design,领域驱动建模)还是分层架构的风

Spring Boot 集成 MyBatis(四)

Spring Boot 集成 MyBatis A.ORM框架是什么? 对象关系映射(Object Relational Mapping,简称 ORM)模式是一种为了解决面向对象与关系数据库存在的 互不匹配的现象技术.简单的说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自 动持久化到关系数据库中. B.为什么需要ORM框架 当开发一个应用程序的时候(不使用 O/R Mapping),可能会写不少数据访问层的代码,用来从数据库保存. 删除.读取对象信息等.在 DAL 中写了很

spring boot集成MyBatis 通用Mapper 使用总结

spring boot集成MyBatis 通用Mapper 使用总结 2019年 参考资料: Spring boot集成 MyBatis 通用Mapper SpringBoot框架之通用mapper插件(tk.mybatis) spring boot 如何优雅的使用mybatis-spring-boot-starter 三分钟让你看懂Springboot 中 Mybatis 的使用 Spring Boot 集成MyBatis__动力节点 ===================== end 原文地

spring boot集成mybatis 自动生成实体类和mapper文件、Dao层

1.创建spring boot集成mybatis请见 2.在resources目录下新键mybatis-generator文件夹,并在文件夹中新键mybatis-generatorConfig.xml文件和mybatis-generatorinit.properties两个文件 mybatis-generatorinit.properties jdbc_driver=oracle.jdbc.driver.OracleDriver jdbc_url=jdbc:oracle:thin:@loclho

spring boot 集成 Mybatis,JPA

相对应MyBatis, JPA可能大家会比较陌生,它并不是一个框架,而是一组规范,其使用跟Hibernate 差不多,原理层面的东西就不多讲了,主要的是应用. Mybatis就不多说了,SSM这三个框架现在基本上都是基本框架了. MyBatis 与 Spring boot 整合时除了添加必要的jar, 插件.在applicatoin.properties/application.yml 中添加相应的配置. 注意的一点就是在启动类中记得添加@MapperScan("com.spSystem.map

Spring Boot集成Mybatis及通用Mapper

集成Mybatis可以通过 mybatis-spring-boot-starter 实现. <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-

Spring Boot集成Mybatis完整实例

步骤: 添加Mybatis依赖: 添加数据库依赖: 配置属性文件: (具体的属性名称可以在jar包中找到) 内容: 建表sql: Mapper文件的头: 集成Mybatis的配置文件中的具体内容可以在mybatis.spring.boot:mybatis-spring-boot-autoconfigure的jar包中找到: Mapper接口上要添加Mybatis的注解@Mapper: 原文地址:https://www.cnblogs.com/niwotaxuexiba/p/10849570.ht

spring boot集成mybatis

1.在pom中添加依赖: #mybatis依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> #mysql <dependency> <group

spring boot集成mybatis需要的相关依赖

<dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- springboot对面向切面编程的支持,包括spring-aop和aspectj --> <de