参考:
http://www.ityouknow.com/springboot/2016/11/06/spring-boo-mybatis.html
https://github.com/pagehelper/pagehelper-spring-boot
1 无xml整合
无xml
整合就是不使用*.xml
文件,全部都是用注解来绑定SQL
。
1.1 引入mybatis-spring-boot-starter
SpringBoot
整合Mybatis
,首先需要引入mybatis-spring-boot-starter
依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
mybatis-spring-boot-starter
将会:
- 自动检测存在的
DataSource
。 - 将会使用
SqlSessionFactoryBean
创建并注册一个SqlSessionFactory
实例,并配置DataSource
。 - 将会基于
SqlSessionFactory
创建并注册一个SqlSessionTemplate
实例。 - 自动扫描
@Mapper
注解类,并关联SqlSessionTemplate
,将它们注册到Spring Context
中。
1.2 数据源和mybatis配置
这里以postgresql
为例。
首先,需要在pom.xml
中引入postgresql
驱动:
<!-- postgresql驱动 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
然后,需要在application.properties
配置文件中配置数据源:
# 配置数据源
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/springbootstarter?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=postgres
spring.datasource.password=password
如果是MySQL,可以如下所示配置数据源信息:
# 配置数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootstarter?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=Abc123++
进行简单的Mybatis
配置,所有可配置属性请查看 这里 和 这里:
# Mybatis基本配置
# 自动驼峰命名转换
mybatis.configuration.map-underscore-to-camel-case=true
# 设置驱动等待数据库返回response的超时时间,单位(秒)
mybatis.configuration.default-statement-timeout=30
1.3 使用@MapperScan
有两种方法可以让Mybatis
检测到mapper
,也就是Dao
。一种是在每个mapper
上面添加@Mapper
注解,一种是通过在启动类(配置类)上添加@MapperScan
注解来指定mapper
的位置。推荐使用第二种:
可以在启动类Application
上添加@MapperScan
:
@SpringBootApplication
@MapperScan({
"com.tao.springbootstarter.web.dao", "com.tao.springbootstarter.core.dao"})
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
// 执行run方法
app.run(args);
}
}
@MapperScan
支持指定一个或多个package
路径。
1.4 编写Dao
在@MapperScan
指定的package
路径下编写Dao
。
以UserDao
为例:
public interface UserDao {