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

【SpringBoot从初学者到专家的成长08】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/471357.html

相关文章:

  • 天津建设网站c2成绩查询深圳广告制作厂家
  • Ubuntu 磁盘 I/O 监控完全指南
  • wordpress完美迁站教程代理网络工具
  • XR + 文旅:虚实共生,重塑时空,XR技术如何开启文旅产业的新纪元
  • 为网站做一则广告dedecms网站地图模板怎么
  • 前端常用框架及优缺点
  • 使用php做的网站mvc net跳转到另一网站
  • TCP/MQTT简单介绍
  • wordpress加载单页面内容seo如何去做优化
  • 网站建设制作公司都选万维科技做SEO用dede还是wordpress
  • 中山做网站优化赣州网上房地产官网
  • 庐江网站制作手机自媒体网站模板
  • 建网页网站广东推广网络
  • 黑龙江建设集团网站阿里云 cdn wordpress
  • csdn| MySQL
  • 用shopify 做网站空白的网站怎么建设
  • 在直播网站做前端注意营销型网站建设设计服务
  • 一个空间可以做几个网站seo网站排名优化工具
  • 高端网站建设与发展wordpress建站博客园
  • 如何做自己的播报网站初二信息课网站怎么做
  • 构建AI智能体:六十、特征工程行业实践录:金融、电商、医疗的智能化转型
  • 网站建设源码导入福州网站开发cms
  • 软件安装管理
  • 创意产品网站重庆网站
  • 外包做的网站可以直接去收录吗做网站公众号要多少钱
  • 大兴企业官网网站建设咨询python免费看电影的应用
  • Koa.js 完全指南:下一代 Node.js Web 框架
  • PK10如何自己做网站个人网站建立 学生
  • 为什么网站之有首页被收录常见的网站名称有哪些
  • wordpress 设置常规站点地址官方网站建设报价表