# 29\. 使用SQL數據庫
Spring Framework 為使用SQL數據庫提供了廣泛的支持。 從使用JdbcTemplate直接JDBC訪問到完成“對象關系映射”技術,如Hibernate。Spring Data提供了額外的功能,直接從接口創建Repository實現,并使用約定從方法名稱生成查詢。
### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#291-配置datasource)29.1 配置DataSource
Java的javax.sql.DataSource接口提供了使用數據庫連接的標準方法。傳統上,DataSource使用URL和一些憑據來建立數據庫連接。
> 還可以查看更多高級示例的[“操作方法”部分](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#howto-configure-a-datasource),通常可以完全控制DataSource的配置。
#### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2911-嵌入式數據庫支持)29.1.1 嵌入式數據庫支持
使用內存中嵌入式數據庫開發應用程序通常很方便。 顯然,內存數據庫不提供持久化存儲; 您的應用程序啟動時,您將需要初始化數據庫,并在應用程序結束時丟棄數據。
> [“How-to”部分](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#howto-database-initialization)包含如何初始化數據庫
Spring Boot可以自動配置嵌入式?[H2](http://www.h2database.com/),[HSQL](http://hsqldb.org/)?和?[Derby](https://db.apache.org/derby/)?數據庫。 您不需要提供任何連接URL,只需將要使用的嵌入式數據庫的依賴關系包含進去即可。
> 如果您在測試中使用此功能,您可能會注意到,整個測試套件都會重復使用相同的數據庫,而不管您使用的應用程序上下文的數量。 如果要確保每個上下文都有一個單獨的嵌入式數據庫,您應該將spring.datasource.generate-unique-name設置為true。
例如,典型的POM依賴關系是:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
```
> 對于要自動配置的嵌入式數據庫,您需要依賴spring-jdbc。 在這個例子中,它是通過spring-boot-starter-data-jpa傳遞的。
> 如果由于某種原因配置嵌入式數據庫的連接URL,則應注意確保數據庫的自動關閉被禁用。 如果你使用H2,你應該使用DB_CLOSE_ON_EXIT=FALSE這樣做。 如果您使用HSQLDB,則應確保不使用shutdown=true。 禁用數據庫的自動關閉允許Spring Boot控制數據庫何時關閉,從而確保在不再需要訪問數據庫時發生這種情況。
#### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2912-連接到生產環境數據庫)29.1.2 連接到生產環境數據庫
生產數據庫連接也可以使用連接池數據源自動配置。 這是選擇具體實現的算法:
* 我們更喜歡Tomcat連接池DataSource的性能和并發性,所以如果可用,我們總是選擇它。
* 否則,如果HikariCP可用,我們將使用它。
* 如果Tomcat池數據源和HikariCP都不可用,并且如果Commons DBCP可用,我們將使用它,但是我們不建議在生產中使用它,并且不支持它。
* 最后,如果Commons DBCP2可用,我們將使用它。
如果您使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa 的startters,您將自動獲得對tomcat-jdbc的依賴。
> 您可以完全繞過該算法,并通過spring.datasource.type屬性指定要使用的連接池。 如果您在Tomcat容器中運行應用程序,則默認情況下提供tomcat-jdbc,這一點尤為重要。
> 可以隨時手動配置其他連接池。如果您定義自己的DataSource bean,則不會發生自動配置。
DataSource配置由spring.datasource中的外部配置屬性控制。 例如,您可以在application.properties中聲明以下部分:
```
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.url屬性指定url,否則Spring Boot將嘗試自動配置嵌入式數據庫。
> 您通常不需要指定驅動程序類名稱,因為Spring Boot可以從url為大多數數據庫推斷出驅動程序名稱。
> 對于要創建的池數據源,我們需要能夠驗證有效的Driver類是否可用,所以我們在做任何事情之前檢查它。 即 如果您設置spring.datasource.driver-class-name=com.mysql.jdbc.Driver,那么該類必須可加載。
有關更多支持的選項,請參閱?[DataSourceProperties](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java)。 這些是標準選項,無論實際執行情況如何。 還可以使用各自的前綴(spring.datasource.tomcat.*,spring.datasource.hikari.*和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
```
#### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2913-連接到jndi-datasource)29.1.3 連接到JNDI DataSource
如果要將Spring Boot應用程序部署到應用程序服務器,則可能需要使用應用程序服務器內置功能來配置和管理DataSource,并使用JNDI進行訪問。
spring.datasource.jndi-name屬性可以用作spring.datasource.url,spring.datasource.username和spring.datasource.password屬性的替代方法,以從特定的JNDI位置訪問DataSource。 例如,application.properties中的以下部分顯示了如何訪問JBoss AS定義的DataSource:
```
spring.datasource.jndi-name=java:jboss/datasources/customers
```
### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#292-使用jdbctemplate)29.2 使用JdbcTemplate
Spring的JdbcTemplate和NamedParameterJdbcTemplate類是自動配置的,您可以將它們直接連接到您自己的bean中:
```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
@Autowired
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// ...
}
```
### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#293-jpa-和-spring-data)29.3 JPA 和 ‘Spring Data’
Java Persistence API是一種標準技術,可讓您將對象映射到關系數據庫。 spring-boot-starter-data-jpa POM提供了一種快速入門的方法。 它提供以下關鍵依賴:
* Hibernate - 最受歡迎的JPA實現之一。
* Spring Data JPA - 可以輕松實現基于JPA的存儲庫。
* Spring ORMs - 來自Spring Framework的核心ORM支持。
> 我們不會在這里介紹太多的JPA或Spring Data的細節。 您可以從[spring.io](http://spring.io)中查看“[使用JPA訪問數據](https://spring.io/guides/gs/accessing-data-jpa/)”指南,并閱讀[Spring Data JPA](http://projects.spring.io/spring-data-jpa/)和[Hibernate](http://hibernate.org/orm/documentation/)參考文檔。
> 默認情況下,Spring Boot使用Hibernate 5.0.x. 但是,如果您愿意,也可以使用4.3.x或5.2.x。 請參考?[Hibernate 4](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-samples/spring-boot-sample-hibernate4)?和?[Hibernate 5.2](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-samples/spring-boot-sample-hibernate52)?示例,看看如何做到這一點。
#### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2931-實體類)29.3.1 實體類
傳統上,JPA'Entity'類在persistence.xml文件中指定。 使用Spring Boot此文件不是必需的,而是使用“實體掃描”。 默認情況下,將搜索主配置類下面的所有包(用@EnableAutoConfiguration或@SpringBootApplication注解的類)。
任何用@Entity,@Embeddable或@MappedSuperclass注解的類將被考慮。 典型的實體類將如下所示:
```
package com.example.myapp.domain;
import java.io.Serializable;
import javax.persistence.*;
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
// ... additional members, often include @OneToMany mappings
protected City() {
// no-args constructor required by JPA spec
// this one is protected since it shouldn't be used directly
}
public City(String name, String state) {
this.name = name;
this.country = country;
}
public String getName() {
return this.name;
}
public String getState() {
return this.state;
}
// ... etc
}
```
> 您可以使用@EntityScan注解自定義實體掃描位置。 請參見[第77.4節“從Spring配置中分離@Entity定義”](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#howto-separate-entity-definitions-from-spring-configuration)操作方法。
#### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2932-spring-data-jpa-repositories)29.3.2 Spring Data JPA Repositories
Spring Data JPA庫是可以定義用于訪問數據的接口。 JPA查詢是從您的方法名稱自動創建的。 例如,CityRepository接口可以聲明findAllByState(String state)方法來查找給定狀態下的所有城市。
對于更復雜的查詢,您可以使用Spring數據[查詢](http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Query.html)注解來注解您的方法。
Spring數據存儲庫通常從Repository或CrudRepository接口擴展。 如果您正在使用自動配置,將從包含主配置類(通過@EnableAutoConfiguration或@SpringBootApplication注解的包)的包中搜索存儲庫(repositories)。
這是一個典型的Spring數據庫:
```
package com.example.myapp.domain;
import org.springframework.data.domain.*;
import org.springframework.data.repository.*;
public interface CityRepository extends Repository<City, Long> {
Page<City> findAll(Pageable pageable);
City findByNameAndCountryAllIgnoringCase(String name, String country);
}
```
> 我們只是觸及了Spring Data JPA的表面。 有關完整的詳細信息,請查閱其[參考文檔](http://projects.spring.io/spring-data-jpa/)。
#### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2933-創建和刪除jpa數據庫)29.3.3 創建和刪除JPA數據庫
默認情況下,僅當您使用嵌入式數據庫(H2,HSQL或Derby)時才會自動創建JPA數據庫。 您可以使用spring.jpa。*屬性顯式配置JPA設置。 例如,要創建和刪除表,您可以將以下內容添加到application.properties中。
- Part I. Spring Boot 文檔
- Part II. 入門指南
- 8. Spring Boot 介紹
- 9. 系統要求
- 10. 安裝 Spring Boot
- 11. 開發您的第一個Spring Boot應用程序
- 12. 接下來應該讀什么
- Part III. 使用 Spring Boot
- 13. 構建系統
- 14. 構建代碼
- 15. 配置類
- 16. 自動配置
- 17. Spring Beans 和 依賴注入
- 18. 使用@SpringBootApplication注解
- 19. 運行你的應用程序
- 20. 開發工具
- 21. 包裝您的應用程序到生產環境
- 22. 接下來應該讀什么
- Part IV. Spring Boot 功能
- 23. SpringApplication
- 24. 外部配置
- 25. 配置文件(Profiles)
- 26. 日志
- 27. 開發Web應用程序
- 28. Security
- 29. 使用SQL數據庫