引入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
- 自动检测工程中的DataSource
- 创建并注册SqlSessionFactory实例
- 创建并注册SqlSessionTemplate实例
- 自动扫描mappers
配置
数据源
ewriteBatchedStatements=true 开启真正批处理 Oracle 默认开启
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3307/sql?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true
driver-class-name: com.mysql.cj.jdbc.Driver
连接池
spring:
datasource:
hikari:
auto-commit: true
data-source-properties:
# 缓存 SQL 语句
cachePrepStmts: true
# 缓存大小
prepStmtCacheSize: 250
# 缓存 SQL 的长度限制
prepStmtCacheSqlLimit: 2048
# 服务器预编译
useServerPrepStmts: true
pool-name: Hikari
# 最小连接数
minimum-idle: 20
maximum-pool-size: 500
# 等待连接池分配连接的时间 毫秒 默认 30
connection-timeout: 500
# 连接超时的最大 时常 毫秒 默认10分钟
idle-timeout: 60000
# 连接的生命时常 超时没有被使用 则回收 毫秒 默认30分钟
max-lifetime: 30000000
connection-test-query: select 1
Mybatis配置
参考 mybatis-spring-boot-autoconfigure – Introductionhttp://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html
mybatis:
type-aliases-package: com.du.bean
mapper-locations:
- classpath:mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
use-generated-keys: true
lazy-loading-enabled: true
aggressive-lazy-loading: false
logging:
level:
com.du.mapper: DEBUG
指定配置文件XMl
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--使用xml配置sql-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
java配置类
@Configuration
public class MyBatisConfig {
/**
* @return ConfigurationCustomizer
*/
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setMapUnderscoreToCamelCase(true);
}
}
启动类
@SpringBootApplication
@MapperScan(value = "com.du.mapper")
public class DataBase {
public static void main(String[] args) {
SpringApplication.run(DataBase.class);
}
}