SpringBoot借助docker容器的数据库实现jdbc连接
发布日期:2021-05-07 13:38:50 浏览次数:20 分类:精选文章

本文共 2445 字,大约阅读时间需要 8 分钟。

前置工作:

linux虚拟机中启动mysql,然后navicat连接虚拟机的mysql
在这里插入图片描述
创建SpringBoot项目,勾选Spring Web,mysql Driver,JDBC API 这几个组件!
创建application.yml

spring:  datasource:    username: root    password: 123    url: jdbc:mysql://192.168.31.52:3306/jdbc    driver-class-name: com.mysql.cj.jdbc.Driver    server:  port: 8888

验证是否连接成功:

在测试类中写下面的代码:

package org.lzl.bootjdbc;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;@SpringBootTestclass BootjdbcApplicationTests {       @Autowired    DataSource dataSource;    @Test    void contextLoads() throws SQLException {           System.out.println(dataSource.getClass());        Connection connection = dataSource.getConnection();        System.out.println(connection);        connection.close();    }}

在这里插入图片描述

连接成功,可以看出springBoot 2.x之后默认采用的是HikarDataSource连接方式!

SpringBoot在创建连接池后还会运行预定义的SQL脚本文件,具体参考org.springframework.boot.autoconfigure.jdbc.DataSourceInitializationConfiguration配置类,在该类中注册了dataSourceInitializerPostProcessor

可以看出,如果我们没有在配置文件中配置脚本的具体位置,就会在classpath下找schema-all.sql和schema.sql platform获取的是all,platform可以在配置文件中修改

具体查看createSchema()方法和initSchema()方法
initSchema()方法获取的是data-all.sql,data.sql
也可以指定要运行的sql脚本:
在这里插入图片描述
比如我创建了department.sql(命名没有按照默认的规范),只需要在yml中加上指定的语句,容器就会在主类运行时,自动运行该sql:

spring:  datasource:    username: root    password: 123    url: jdbc:mysql://192.168.31.52:3306/jdbc    driver-class-name: com.mysql.cj.jdbc.Driver    initialization-mode: always    schema:      - classpath:department.sqlserver:  port: 8888

启动springboot,发现数据库中生成了department表:

在这里插入图片描述
可以给表插入点数据,用spring jdbcTemplate看看呢能不能取到数据:

package org.lzl.bootjdbc.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;import java.util.Map;@Controllerpublic class HelloController {       //springboot初始化  会自动在ioc中放入JdbcTemplate实例    @Autowired    JdbcTemplate jdbcTemplate;    @ResponseBody    @GetMapping("/query")    public Map
map(){ String sql = "select *from department"; List
> map = jdbcTemplate.queryForList(sql); return map.get(0); }}

发送请求验证:

在这里插入图片描述
很成功!!!!!!!

上一篇:SpringBoot采用Druid数据源连接
下一篇:docker技术

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月06日 12时10分42秒