- Spring Boot 2.0 Cookbook(Second Edition)
- Alex Antonov
- 379字
- 2021-06-24 19:24:38
How it works...
Even though, by default, Spring Boot makes certain assumptions about the database configuration by examining the classpath for the presence of supported database drivers, it provides you with easy configuration options to tweak the database access via a set of exposed properties grouped under spring.datasource.
The things that we can configure are url, username, password, driver-class-name, and so on. If you want to consume the datasource from a JNDI location, where an outside container creates it, you can configure this using the spring.datasource.jndi-name property. The complete set of possible properties is fairly large, so we will not go into all of them. However, we will cover more options in Chapter 5, Application Testing, where we will talk about mocking data for application tests using a database.
If you want to connect to a regular (non-embedded) database, besides just having the appropriate driver library in the classpath, we need to specify the driver of our choice in the configuration. The following code snippet is what the configuration to connect to MySQL would resemble:
spring.datasource.driver-class-name: com.mysql.jdbc.Driver spring.datasource.url:
jdbc:mysql://localhost:3306/springbootcookbook spring.datasource.username: root spring.datasource.password:
If we wanted Hibernate to create the schema automatically, based on our entity classes, we would need to add the following line to the configuration:
spring.jpa.hibernate.ddl-auto=create-drop
You can go even further in the abstraction layer and, instead of autowiring a DataSource object, you could go straight for JdbcTemplate. This would instruct Spring Boot to automatically create a DataSource and then create a JdbcTemplate wrapping the datasource, thus providing you with a more convenient way of interacting with a database in a safe way. The code for JdbcTemplate is as follows:
@Autowired private JdbcTemplate jdbcTemplate;
You can also look in the spring-boot-autoconfigure source at an org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration file to see the code behind the datasource creation magic.
- Hands-On Machine Learning with Microsoft Excel 2019
- 云計算環境下的信息資源集成與服務
- 信息系統與數據科學
- 使用GitOps實現Kubernetes的持續部署:模式、流程及工具
- Proxmox VE超融合集群實踐真傳
- Expert Python Programming(Third Edition)
- 大數據分析:R基礎及應用
- 企業大數據處理:Spark、Druid、Flume與Kafka應用實踐
- Arquillian Testing Guide
- 數據產品經理寶典:大數據時代如何創造卓越產品
- Flume日志收集與MapReduce模式
- AutoCAD基礎與應用精品教程(2008版)
- MATLAB基礎及其應用教程
- Hadoop與大數據挖掘
- Foxtable數據庫應用開發寶典