栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot访问数据库(springboot配置数据源是如何实现的)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot访问数据库(springboot配置数据源是如何实现的)

一、SpringBoot数据访问之概述和基础环境搭建 1、概述

Spring Boot默认采用整合SpringData的方式统一处理数据访问层,
通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,
从而达到简化数据层的操作。

2、SpringBoot提供的常见数据库依赖启动器
   名称                               对应数据库
spring-boot-starter-data-jpa        Spring Data JPA
                                    Hibernate
spring-boot-starter-data-mongodb    MongoDB
                                    Spring Data MongoDB
spring-boot-starter-data-neo4j      Neo4j图数据库
                                    Spring Data Neo4j
spring-boot-starter-data-redis      Redis
二、Spring Boot整合MyBatis 1、基础环境 (1)数据准备
创建数据库、数据表并插入一定的数据。
(2)创建项目,引入相应的启动器
使用Spring Initializr的方式构建项目,选择MySQL和MyBatis依赖,编写实体类。
(3)编写配置文件
在配置文件中进行数据库连接配置以及进行第三方数据源的默认参数覆盖。
2、过程 (1)首先在数据库里创建对应的数据库表,然后插入相关数据 (2)创建项目,引入MySQL和MyBatis的依赖启动器 (3)编写实体类

例如:编写了Comment和Article两个实体类

public class Comment{
    private Integer ID;
    private String content;
    private IntegeraId;
}
public class Article{
    private Integer id;
    private String title;
    private String content;
    private ListcommentList;
}
3、编写配置文件 (1)在全局配置文件中进行数据库连接配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root (数据库用户名)
spring.datasource.password=123456 (数据库密码)

(2)如果想要设置新的数据源

例如:(设置数据源类型配置,下面以阿里巴巴的Druid数据源为例)


   com.alibaba
   druid-spring-boot-starter
   1.1.10

然后,对数据源默认值进行修改

数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDatasource
初始化连接数
spring.datasource.initialSize=20
最小空闲数
spring.datasource.minIdle=20
最大连接数
spring.datasource.maxActive=200

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/776058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号