【SpringBoot笔记6】SpringBoot整合Mybatis和PageHelper

参考:

官方文档

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 {
   

    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值