springboot 学习(六) springboot整合mybatis
官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
导入依赖,mybatis对于spring是第三方的,所以是mybatis-xxx 开头
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
配置的数据库源,使用druid的数据源,同时配置文件,也可以配置mybatis信息(下面最后两行),分别配置了类的别名,已经mapper.xml文件路径
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
filters: wall,stat,log4j
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
mybatis:
type-aliases-package: com.hys.pojo
mapper-locations: userMapper.xml
整合特殊点:dao层接口类需要使用@Mapper注解,表明这是一个mybatis的mapper,同时也进行了注册了
@Mapper
public interface userMapper {
public List<User> getAllUser();
}
mapper.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hys.mapper.userMapper">
<select id="getAllUser" resultType="user">
select * from student
</select>
</mapper
测试使用:简单直接@Autowired装配接口,然后调用方法
@Autowired
userMapper userMapper;
@GetMapping("/mybatis")
public List<User> mybatis(){
List<User> allUser = userMapper.getAllUser();
System.out.println(allUser);
return allUser;
}

浙公网安备 33010602011771号