在上篇文章中
Spring boot 学习之路(一)构建第一个Spring Boot
我已经介绍了如何使用IDEA 来搭建一个Spring boot 项目,接下来我将介绍一下在Spring boot
中我们如何将它与myBatis 结合;
我们都知道mybatis 是一个轻量级的持久层框架,它具有非常强大以及灵活的功能!所以我们在我们选择持久层框架的时候,mybatis常常是我们的不二之选!接下来我就来为大家介绍一下 Springboot是如何与mybatis结合的!
首先是建立一个普通的Springboot项目之后再pom.xml中加入mybatis的包
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
之后我们在application.yml文件中加入数据源配置:
#端口号
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/cms?characterEncoding=utf8
username: root
password:<数据库密码>
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
mybatis:
#xml 文件路径
mapper-locations: classpath:mapping/*.xml
#扫描的实体类路径
type-aliases-package: com.ljw.entity
之后我们根据路径创建实体类和xml文件,和在spring mvc 中配置mybatis一样 调用也是一样。
值得注意的是我们在他的启动类中我们需要加入MapperScan 来扫描他的dao类,只有这样我们才能够访问。
好了到此mybatis就已经集成在我们的Springboot了 ,还等什么!赶紧去试试吧