当前位置: 首页 > news >正文

【碎片化学习】SpringBoot数据库驱动介绍配置方法和代码

在Spring Boot中连接数据库是构建企业级应用程序的一个关键步骤。Spring Boot简化了数据库连接和操作,支持多种主流数据库(如MySQL、PostgreSQL、Oracle、SQL Server等)。

一、主流的数据库驱动

Spring Boot支持多种常见的关系型数据库。以下是几个常用数据库及其对应的数据库驱动:

  1. MySQL

    • 驱动类:com.mysql.cj.jdbc.Driver
    • 依赖:spring-boot-starter-data-jpaspring-boot-starter-jdbc,以及 MySQL 驱动。
  2. PostgreSQL

    • 驱动类:org.postgresql.Driver
    • 依赖:spring-boot-starter-data-jpaspring-boot-starter-jdbc,以及 PostgreSQL 驱动。
  3. Oracle

    • 驱动类:oracle.jdbc.OracleDriver
    • 依赖:spring-boot-starter-data-jpaspring-boot-starter-jdbc,以及 Oracle 驱动。
  4. SQL Server

    • 驱动类:com.microsoft.sqlserver.jdbc.SQLServerDriver
    • 依赖:spring-boot-starter-data-jpaspring-boot-starter-jdbc,以及 SQL Server 驱动。

二、yml配置方法

Spring Boot支持两种配置方式:application.propertiesapplication.yml。下面是使用 yml 配置数据库连接的示例:

application.yml 配置示例
spring:datasource:url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTCusername: rootpassword: rootpassworddriver-class-name: com.mysql.cj.jdbc.Driverhikari:maximum-pool-size: 10minimum-idle: 5idle-timeout: 30000hikari:connection-timeout: 30000validation-timeout: 5000jpa:hibernate:ddl-auto: updateproperties:hibernate:dialect: org.hibernate.dialect.MySQL5InnoDBDialectshow_sql: trueformat_sql: true# 配置数据源类型:JPA、JDBC等data:jpa:repositories:enabled: true

三、properties配置方法

如果你更倾向于使用 .properties 配置文件,可以参考以下配置示例:

application.properties 配置示例
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=rootpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.validation-timeout=5000spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true

四、常用的配置参数说明

  1. spring.datasource.url:数据库的连接URL,包括协议、IP、端口、数据库名及其它连接参数。
  2. spring.datasource.username:数据库的用户名。
  3. spring.datasource.password:数据库的密码。
  4. spring.datasource.driver-class-name:数据库驱动类名(比如MySQL为com.mysql.cj.jdbc.Driver)。
  5. spring.jpa.hibernate.ddl-auto:JPA的DDL自动生成方式。常见值:
    • none:不自动生成。
    • update:如果数据库表结构发生变化,自动更新表结构。
    • create:每次启动时,重新创建数据库。
    • create-drop:启动时创建数据库,关闭时删除。
  6. spring.jpa.properties.hibernate.dialect:数据库方言,用于优化SQL生成。例如,MySQL使用MySQL5InnoDBDialect
  7. spring.jpa.properties.hibernate.show_sql:是否打印SQL日志。
  8. spring.jpa.properties.hibernate.format_sql:格式化SQL输出,便于调试。

五、数据库连接优化建议

  1. 连接池配置:使用HikariCP连接池,它是Spring Boot的默认连接池,性能优越。通过spring.datasource.hikari配置最大连接数、空闲连接数和连接超时等参数,可以提升数据库连接性能。

  2. JPA性能优化

    • 设置hibernate.jdbc.batch_size:开启批量操作,减少数据库交互次数。
    • hibernate.cache.use_second_level_cache:启用二级缓存,减少查询次数。
  3. 数据库连接超时和重试机制

    • 配置合理的spring.datasource.hikari.connection-timeoutspring.datasource.hikari.idle-timeout,防止连接池因长时间无请求而断开。
    • 使用连接池的自动重连功能,避免连接丢失。

六、代码访问数据库的增删改查(CRUD)实例

在Spring Boot中,通常使用JPA(Java Persistence API)来操作数据库,下面给出一个简单的增删改查(CRUD)操作的代码示例。

1. 实体类
import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class User {@Idprivate Long id;private String name;private String email;// Getters and Setters
}
2. Repository接口
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository<User, Long> {// 可以自定义查询方法User findByEmail(String email);
}
3. Service层
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Optional;@Service
public class UserService {@Autowiredprivate UserRepository userRepository;// 增加public User addUser(User user) {return userRepository.save(user);}// 查询所有public List<User> getAllUsers() {return userRepository.findAll();}// 查询单个public Optional<User> getUserById(Long id) {return userRepository.findById(id);}// 删除public void deleteUser(Long id) {userRepository.deleteById(id);}// 更新public User updateUser(Long id, User userDetails) {User user = userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));user.setName(userDetails.getName());user.setEmail(userDetails.getEmail());return userRepository.save(user);}
}
4. Controller层
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.Optional;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;// 增加@PostMappingpublic User addUser(@RequestBody User user) {return userService.addUser(user);}// 查询所有@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}// 查询单个@GetMapping("/{id}")public Optional<User> getUserById(@PathVariable Long id) {return userService.getUserById(id);}// 删除@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.deleteUser(id);}// 更新@PutMapping("/{id}")public User updateUser(@PathVariable Long id, @RequestBody User user) {return userService.updateUser(id, user);}
}

七、写在最后

通过配置application.ymlapplication.properties文件,Spring Boot可以很方便地连接到主流数据库。通过JPA,开发者能够轻松地进行数据库的增、删、改、查操作,并能结合HikariCP优化连接池性能。

http://www.dtcms.com/a/470595.html

相关文章:

  • 设计模式篇之 适配器模式 Adapter
  • 小程序怎么制作自己的小程序seo长尾关键词优化
  • 网站备案号规则中核集团2023校园招聘信息
  • postman 做接口测试之学习笔记
  • 做网站要买多少服务器空间有什么做家纺的网站
  • 【编号26】青藏高原地理空间全套数据集(矢量边界、子流域、行政边界、水系等)
  • loguru 和 logging 的详细对比
  • 番禺移动网站建设百度快照投诉中心官网
  • 调试去符号化/strip 过的二进制的调试方法
  • 大连建设局网站地址怎么将自己房子投入网站做民宿
  • 新河网站旅游网站策划方案
  • 建网站备案好麻烦长春市建设工程造价管理协会网站
  • 东莞设计网站建设方案南京网站建设排名
  • Dirty COW容器逃逸漏洞渗透实战:原理+复现 (CVE-2016-5195)
  • 2010 866数据结构 算法设计题——链表,二叉树
  • 对海尔网站建设水平的评价长沙网站备案
  • Codeforces Round 1057 (Div. 2)(A-D)
  • 微信网站备案wordpress step2
  • XSS 漏洞全解析:从原理到实战
  • 傻瓜式 建网站软件外包公司人数
  • Nestjs service 对应token的作用范围
  • Google 智能体设计模式:评估与监控
  • 如何屏蔽网站ipwordpress 商城模板下载
  • OpenMM 8 安装与上手指南
  • 网站建设跟网站开发有什么区别吗832网络销售平台
  • 力扣热题100道49字母异位词分组
  • sql优化进阶
  • 网站灰色建设网销怎么找客户资源
  • 库易网网站郑州网站关键词优化公司
  • n8n Code节点模式选择指南:Run Once for All Items与Run Once for Each Item