<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 使用JPA訪問數據 本指南將引導您完成構建使用Spring Data JPA來在關系數據庫中存儲和檢索數據的應用程序的過程。 ## 你會建立什么 您將構建一個應用程序來存儲 `Customer` 基于內存的數據庫中的POJO(普通的舊Java對象)。 ## 你需要什么 * 約15分鐘 * 最喜歡的文本編輯器或IDE * [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本 * [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi) * 您還可以將代碼直接導入到IDE中: * [彈簧工具套件(STS)](https://spring.io/guides/gs/sts) * [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) ## 如何完成本指南 像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。 要 **從頭開始** ,請繼續進行“ [從Spring Initializr開始”](https://spring.io/guides/gs/accessing-data-jpa/#scratch) 。 要 **跳過基礎知識** ,請執行以下操作: * [下載](https://github.com/spring-guides/gs-accessing-data-jpa/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-accessing-data-jpa.git](https://github.com/spring-guides/gs-accessing-data-jpa.git)` * 光盤進入 `gs-accessing-data-jpa/initial` * 繼續 [定義一個簡單實體](https://spring.io/guides/gs/accessing-data-jpa/#initial) 。 **完成后** ,您可以根據中的代碼檢查結果 `gs-accessing-data-jpa/complete`. ## 從Spring Initializr開始 如果您使用Maven,請訪問 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-jpa&name=accessing-data-jpa&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-jpa&dependencies=data-jpa,h2) 以生成具有所需依賴項(JPA和H2)的新項目。 以下清單顯示了 `pom.xml` 選擇Maven時創建的文件: ~~~ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ~~~ If you use Gradle, visit the [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=demo&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&dependencies=data-jpa,h2) to generate a new project with the required dependencies (JPA and H2). The following listing shows the `build.gradle` file created when you choose Gradle: ~~~ plugins { id 'org.springframework.boot' version '2.4.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.h2database:h2' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ~~~ 配置該項??目以適合本教程中的示例。 ### 手動初始化(可選) 如果要手動初始化項目而不是使用前面顯示的鏈接,請按照以下步驟操作: 1. 導航到 [https://start.spring.io](https://start.spring.io) 。 該服務提取應用程序所需的所有依賴關系,并為您完成大部分設置。 2. 選擇Gradle或Maven以及您要使用的語言。 本指南假定您選擇了Java。 3. 單擊 **Dependencies,** 然后選擇 選擇 **Spring Data JPA** ,然后 **H2 Database** 。 4. 點擊 **生成** 。 5. 下載生成的ZIP文件,該文件是使用您的選擇配置的Web應用程序的存檔。 如果您的IDE集成了Spring Initializr,則可以從IDE中完成此過程。 ## 定義一個簡單實體 在此示例中,您存儲 `Customer`對象,每個對象都標注為JPA實體。 以下清單顯示了Customer類(在 `src/main/java/com/example/accessingdatajpa/Customer.java`): ~~~ package com.example.accessingdatajpa; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String firstName; private String lastName; protected Customer() {} public Customer(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format( "Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } public Long getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } ~~~ 在這里你有一個 `Customer` 具有三個屬性的類: `id`, `firstName`, 和 `lastName`。 您也有兩個構造函數。 默認構造函數僅出于JPA的目的而存在。 您不直接使用它,因此將其指定為 `protected`。 另一個構造函數是您用來創建的實例的構造函數 `Customer` 保存到數據庫。 這 `Customer` 該類帶有注釋 `@Entity`,表明它是一個JPA實體。 (因為沒有 `@Table` 注釋存在,假定此實體已映射到名為的表 `Customer`.) 這 `Customer` 對象的 `id` 屬性帶有注釋 `@Id`因此JPA會將其識別為對象的ID。 這 `id` 屬性也帶有注釋 `@GeneratedValue` 表示應該自動生成ID。 其他兩個屬性, `firstName` 和 `lastName`,不加注解。 假定它們映射到與屬性本身共享相同名稱的列。 方便的 `toString()` 方法打印出客戶的屬性。 ## 創建簡單查詢 Spring Data JPA專注于使用JPA將數據存儲在關系數據庫中。 它最引人注目的功能是能夠在運行時從存儲庫界面自動創建存儲庫實現。 要了解它是如何工作的,請創建一個與 `Customer` 實體如下清單(在 `src/main/java/com/example/accessingdatajpa/CustomerRepository.java`)顯示: ~~~ package com.example.accessingdatajpa; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface CustomerRepository extends CrudRepository<Customer, Long> { List<Customer> findByLastName(String lastName); Customer findById(long id); } ~~~ `CustomerRepository` 擴展 `CrudRepository`界面。 與其一起使用的實體和ID的類型, `Customer` 和 `Long`,是在的通用參數中指定的 `CrudRepository`。 通過擴展 `CrudRepository`, `CustomerRepository` 繼承了幾種使用的方法 `Customer` 持久性,包括保存,刪除和查找的方法 `Customer` 實體。 Spring Data JPA還允許您通過聲明其他方法的方法簽名來定義它們。 例如, `CustomerRepository` 包括 `findByLastName()` 方法。 在典型的Java應用程序中,您可能希望編寫一個實現 `CustomerRepository`。 但是,這就是使Spring Data JPA如此強大的原因:您無需編寫存儲庫接口的實現。 當您運行應用程序時,Spring Data JPA將創建一個實現。 現在,您可以連接此示例并查看其外觀! ## 創建一個應用程序類 Spring Initializr為應用程序創建一個簡單的類。 以下清單顯示了Initializr為此示例創建的類(在 `src/main/java/com/example/accessingdatajpa/AccessingDataJpaApplication.java`): ~~~ package com.example.accessingdatajpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AccessingDataJpaApplication { public static void main(String[] args) { SpringApplication.run(AccessingDataJpaApplication.class, args); } } ~~~ `@SpringBootApplication` 是一個方便注釋,它添加了以下所有內容: * `@Configuration`:將類標記為應用程序上下文的Bean定義的源。 * `@EnableAutoConfiguration`:告訴Spring Boot根據類路徑設置,其他bean和各種屬性設置開始添加bean。 例如,如果 `spring-webmvc` 在類路徑上,此注釋將應用程序標記為Web應用程序并激活關鍵行為,例如設置 `DispatcherServlet`. * `@ComponentScan`:告訴Spring在服務器中尋找其他組件,配置和服務 `com/example` 包,讓它找到控制器。 這 `main()` 方法使用Spring Boot的 `SpringApplication.run()`啟動應用程序的方法。 您是否注意到沒有一行XML? 沒有 `web.xml`文件。 該Web應用程序是100%純Java,因此您無需處理任何管道或基礎結構。 現在,您需要修改Initializr為您創建的簡單類。 為了獲得輸出(在本例中為控制臺),您需要設置一個記錄器。 然后,您需要設置一些數據并將其用于生成輸出。 以下清單顯示了成品 `AccessingDataJpaApplication` 類(在 `src/main/java/com/example/accessingdatajpa/AccessingDataJpaApplication.java`): ~~~ package com.example.accessingdatajpa; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class AccessingDataJpaApplication { private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class); public static void main(String[] args) { SpringApplication.run(AccessingDataJpaApplication.class); } @Bean public CommandLineRunner demo(CustomerRepository repository) { return (args) -> { // save a few customers repository.save(new Customer("Jack", "Bauer")); repository.save(new Customer("Chloe", "O'Brian")); repository.save(new Customer("Kim", "Bauer")); repository.save(new Customer("David", "Palmer")); repository.save(new Customer("Michelle", "Dessler")); // fetch all customers log.info("Customers found with findAll():"); log.info("-------------------------------"); for (Customer customer : repository.findAll()) { log.info(customer.toString()); } log.info(""); // fetch an individual customer by ID Customer customer = repository.findById(1L); log.info("Customer found with findById(1L):"); log.info("--------------------------------"); log.info(customer.toString()); log.info(""); // fetch customers by last name log.info("Customer found with findByLastName('Bauer'):"); log.info("--------------------------------------------"); repository.findByLastName("Bauer").forEach(bauer -> { log.info(bauer.toString()); }); // for (Customer bauer : repository.findByLastName("Bauer")) { // log.info(bauer.toString()); // } log.info(""); }; } } ~~~ 這 `AccessingDataJpaApplication` 類包括一個 `demo()` 的方法 `CustomerRepository`通過一些測試。 首先,它獲取 `CustomerRepository`從Spring應用程序上下文中。 然后節省了 `Customer` 對象,展示了 `save()`方法并設置一些要使用的數據。 接下來,它調用 `findAll()` 取全部 `Customer`數據庫中的對象。 然后它調用 `findById()` 取一個 `Customer`通過其ID。 最后,它調用 `findByLastName()`查找姓氏為“寶華”的所有客戶。 這 `demo()` 方法返回一個 `CommandLineRunner` 在應用程序啟動時自動運行代碼的bean。 默認情況下,Spring Boot啟用JPA存儲庫支持并在包(及其子包)中查找 @SpringBootApplication位于。 如果您的配置在不可見的程序包中有JPA存儲庫接口定義,則可以使用以下方法指出備用程序包: @EnableJpaRepositories 及其類型安全 basePackageClasses=MyRepository.class 范圍。 ## 建立可執行的JAR 您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。 如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示: ~~~ java -jar build/libs/gs-accessing-data-jpa-0.1.0.jar ~~~ 如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示: ~~~ java -jar target/gs-accessing-data-jpa-0.1.0.jar ~~~ 此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。 運行應用程序時,應該看到類似于以下內容的輸出: ~~~ == Customers found with findAll(): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=2, firstName='Chloe', lastName='O'Brian'] Customer[id=3, firstName='Kim', lastName='Bauer'] Customer[id=4, firstName='David', lastName='Palmer'] Customer[id=5, firstName='Michelle', lastName='Dessler'] == Customer found with findById(1L): Customer[id=1, firstName='Jack', lastName='Bauer'] == Customer found with findByLastName('Bauer'): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=3, firstName='Kim', lastName='Bauer'] ~~~ ## 概括 恭喜你! 您已經編寫了一個簡單的應用程序,該應用程序使用Spring Data JPA將對象保存到數據庫中并從數據庫中獲取它們,而所有這些都無需編寫具體的存儲庫實現。 如果您想輕松地使用基于超媒體的RESTful前端公開JPA存儲庫,則可能需要閱讀 使用REST訪問JPA數據 。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看