Spring Boot 访问数据库

版权声明:本文为博主原创文章,转载请标注出处。 https://blog.csdn.net/qq27Ke/article/details/81912128

Spring框架为访问数据库提供了很好的扩展性支持,从直接使用 JdbcTemplate的方式到对象关系映射技术例如hibernate。Spring Data提供了一些额外的功能,比如Repository实现了直接通过接口的方法名生成查询转换。

对嵌入式数据库的支持

使用内存中的嵌入式数据库开发应用程序通常是方便的。显然,在内存数据库中不提供持久存储。当应用程序启动时,您需要填充数据库,并准备在应用程序结束时丢弃数据。
Spring Boot 通过自动配置支持H2,HSQL,和Derby数据库的支持,只需要加载相关依赖和提供连接url即可。

连接生产数据库

生产数据库连接通常使用数据库连接池来管理,Spring Boot 使用下面的算法来指定一个特定的数据库连接池的实现:

1,我们考虑 HikariCP 的高性能和高并发的支持,如果HikariCP可用,默认使用它。
2,除此之外,如果tomcat的连接池可用,我们可以选则tomcat.
3,如果以上两种都不可用,选择使用Commons DBCP2。

如果我们项目中加载了spring-boot-starter-jdbc或者spring-boot-starter-data-jpa依赖,项目启动时会自动加载HikariCP的依赖。

配置数据源

数据源连接配置在application.properties中通过spring.datasource.*来配置,例如:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

查看数据源连接属性,可以配置更多的选项,可以通过各自的属性前缀来设置他们特定的属性(spring.datasource.hikari.*, spring.datasource.tomcat.*,和spring.datasource.dbcp2.*)比如使用tomcat 连接池,你可以定制化自己的设置,例如:

# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.tomcat.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=50

# Validate the connection before borrowing it from the pool.
spring.datasource.tomcat.test-on-borrow=true

使用JNDI的方式建立连接池

如果将一个Spring Boot应该部署到应用服务器上,你也可以通过应用服务器内置的特性来配置和管理数据源(JNDI),使用这种方式,只需要在application.properties中配置spring.datasource.jndi-name:

spring.datasource.jndi-name=java:jboss/datasources/customers

猜你喜欢

转载自blog.csdn.net/qq27Ke/article/details/81912128