Spring Boot 数据访问

一、使用默认的Hikari和H2

Spring Boot 默认使用 Hikari 连接池和 H2 内存数据库。

1.1 添加坐标依赖

<!-- jdbc默认采用hikari连接池 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- H2内存数据库自动连接 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

1.2 测试连接代码

@Slf4j
@SpringBootApplication
public class Demo1Application implements CommandLineRunner {
    @Autowired
    private DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info(dataSource.toString());
        Connection conn = dataSource.getConnection();

        log.info(conn.toString());
        conn.close();
    }
}

1.3 使用内存表

schema.sql 和 data.sql 与 application.yum 位于同一目录,自动加载。
文件名 作用
schema.sql 创建一张或多张表
data.sql 初始化表格数据

二、使用Druid连接池

2.1 添加坐标依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

2.2 配置连接池类型

application.properties

# 不指定type也可以,实测即使指定hikari也无效。
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

三、使用MySQL数据库

3.1 添加坐标依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

3.2 配置数据源

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=你的密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

参考链接

1、Spring Boot 集成教程

评论

暂无评论