Spring Boot开发(2)——Spring Boot整合Mybatis

Mybatis是常用的持久层框架,体验Spring Boot的同时不免需要将Mybatis整合进去

引入maven依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>
      <version>2.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>
  </dependencies>

本文用的是HikariCP连接池,也可以使用其他连接池

数据源属性

在application.properties中添加

datasource.pool.jdbcUrl=jdbc:mysql://
datasource.pool.username=root
datasource.pool.password=
datasource.pool.maximumPoolSize=100

配置一个Mybatis配置

@Configuration
@EnableTransactionManagement
public class MybatisConfig {
    @Bean
    @ConfigurationProperties(prefix = "datasource.pool")
    public DataSource dataSource(){
        return new HikariDataSource();
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }
}

@EnableTransactionManagement开启事务管理

配置mapper

@Mapper
public interface StudentMapper {
    @Select("select * from student")
    @ResultType(value = Student.class)
    List<Student> getAll();
}

@ComponentScan会自动扫描@Mapper注解的类
也可以用@MapperScan来指定

@MapperScan(basePackages = "com.drafthj.test")
public class MybatisConfig {
        ...
}

接下来就可以直接使用Mapper类来操作了

@Autowired
private StudentMapper studentMapper;

使用xml文件配置

1、可以在application.properties中mybatis.config-location=来指定文件位置
2、sqlSessionFactoryBean.setConfigLocation()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,347评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,054评论 6 342
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 11,140评论 0 4
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 4,563评论 0 2
  • Previously on prison break. 越狱是一部由美国福克斯电视网播放的悬疑类情节电视系列剧。该...
    二三三三三阅读 3,315评论 2 2