<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國際加速解決方案。 廣告
                # Spring Boot `@Repository` > 原文: [http://zetcode.com/springboot/repository/](http://zetcode.com/springboot/repository/) Spring Boot `@Repository`教程顯示了如何在 Spring 應用中使用`@Repository`注解。 Spring 是流行的 Java 應用框架,而 Spring Boot 是 Spring 的演進,可以幫助輕松地創建獨立的,生產級的基于 Spring 的應用。 ## `@Repository` `@Repository`是 Spring 注解,指示裝飾的類是存儲庫。 存儲庫是一種用于封裝存儲,檢索和搜索行為的機制,該機制模仿對象的集合。 它是`@Component`注解的一種特殊功能,允許通過類路徑掃描自動檢測實現類。 `@ComponentScan`確保找到用`@Component`和其派生詞包括`@Repository`裝飾的類并將其注冊為 Spring Bean。 `@ComponentScan`自動包含在`@SpringBootApplication`中。 ## Spring Boot `@Repository`示例 以下應用演示了`@Repository`的用法。 它向用戶顯示 HTML 表中的國家/地區列表。 在本應用中,我們使用 Spring Boot 版本 2.1.0。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ ├───controller │ │ │ MyController.java │ │ ├───model │ │ │ Country.java │ │ ├───repository │ │ │ CountryRepository.java │ │ └───service │ │ CountryService.java │ │ ICountryService.java │ └───resources │ │ application.yml │ │ import.sql │ ├───static │ │ index.html │ └───templates │ showCountries.ftl └───test └───java ``` 這是項目結構。 `pom.xml` ```java <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>repositoryex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 這是 Maven 構建文件。 `h2`依賴項包括 H2 數據庫驅動程序。 Spring Boot 啟動器是一組方便的依賴項描述符,可以極大地簡化 Maven 配置。 `spring-boot-starter-parent`具有 Spring Boot 應用的一些常用配置。 `spring-boot-devtools`包含一些 Spring Boot 開發者工具。 `spring-boot-starter-web`支持經典和 RESTFul Web 應用。 `spring-boot-starter-web-freemarker`是使用 Freemarker 模板引擎構建 Web 應用的入門工具。 它使用 Tomcat 作為默認的嵌入式容器。 `spring-boot-starter-data-jpa`是將 Spring Data JPA 與 Hibernate 結合使用的入門工具。 `spring-boot-maven-plugin`在 Maven 中提供了 Spring Boot 支持,使我們可以打包可執行的 JAR 或 WAR 檔案。 它的`spring-boot:run`目標運行 Spring Boot 應用。 `resources/application.yml` ```java server: port: 8086 servlet: context-path: /SpringBootRepository spring: main: banner-mode: "off" jpa: database: h2 hibernate: dialect: org.hibernate.dialect.H2Dialect ddl-auto: create-drop logging: level: org: springframework: ERROR ``` 在`application.yml`文件中,我們編寫了 Spring Boot 應用的各種配置設置。 `port`設置服務器端口和`context-path`上下文路徑(應用名稱)。 完成這些設置后,我們可以通過`localhost:8086/SpringBootRepository/`訪問該應用。 使用`banner-mode`屬性,我們可以關閉 Spring 橫幅。 JPA `database`值指定要操作的目標數據庫。 在本例中,我們指定了 Hibernate 方言`org.hibernate.dialect.H2Dialect`。 `ddl-auto`是數據定義語言模式; `create-drop`選項將自動創建和刪除數據庫模式。 H2 數據庫在內存中運行。 另外,我們將 spring 框架的日志記錄級別設置為`ERROR`。 在`application.yml`文件位于中`src/main/resources`目錄。 `resources/import.sql` ```java INSERT INTO countries(name, population) VALUES('China', 1382050000); INSERT INTO countries(name, population) VALUES('India', 1313210000); INSERT INTO countries(name, population) VALUES('USA', 324666000); INSERT INTO countries(name, population) VALUES('Indonesia', 260581000); INSERT INTO countries(name, population) VALUES('Brazil', 207221000); INSERT INTO countries(name, population) VALUES('Pakistan', 196626000); INSERT INTO countries(name, population) VALUES('Nigeria', 186988000); INSERT INTO countries(name, population) VALUES('Bangladesh', 162099000); INSERT INTO countries(name, population) VALUES('Nigeria', 186988000); INSERT INTO countries(name, population) VALUES('Russia', 146838000); INSERT INTO countries(name, population) VALUES('Japan', 126830000); INSERT INTO countries(name, population) VALUES('Mexico', 122273000); INSERT INTO countries(name, population) VALUES('Philippines', 103738000); INSERT INTO countries(name, population) VALUES('Ethiopia', 101853000); INSERT INTO countries(name, population) VALUES('Vietnam', 92700000); INSERT INTO countries(name, population) VALUES('Egypt', 92641000); INSERT INTO countries(name, population) VALUES('Germany', 82800000); INSERT INTO countries(name, population) VALUES('the Congo', 82243000); INSERT INTO countries(name, population) VALUES('Iran', 82800000); INSERT INTO countries(name, population) VALUES('Turkey', 79814000); INSERT INTO countries(name, population) VALUES('Thailand', 68147000); INSERT INTO countries(name, population) VALUES('France', 66984000); INSERT INTO countries(name, population) VALUES('United Kingdom', 60589000); INSERT INTO countries(name, population) VALUES('South Africa', 55908000); INSERT INTO countries(name, population) VALUES('Myanmar', 51446000); INSERT INTO countries(name, population) VALUES('South Korea', 68147000); INSERT INTO countries(name, population) VALUES('Colombia', 49129000); INSERT INTO countries(name, population) VALUES('Kenya', 47251000); INSERT INTO countries(name, population) VALUES('Spain', 46812000); INSERT INTO countries(name, population) VALUES('Argentina', 43850000); INSERT INTO countries(name, population) VALUES('Ukraine', 42603000); INSERT INTO countries(name, population) VALUES('Sudan', 41176000); INSERT INTO countries(name, population) VALUES('Algeria', 40400000); INSERT INTO countries(name, population) VALUES('Poland', 38439000); ``` 模式是由 Hibernate 自動創建的。 之后,將執行`import.sql`文件以將數據填充到表中。 `com/zetcode/model/Country.java` ```java package com.zetcode.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.util.Objects; @Entity @Table(name = "countries") public class Country { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int population; public Country() { } public Country(Long id, String name, int population) { this.id = id; this.name = name; this.population = population; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Country country = (Country) o; return population == country.population && Objects.equals(id, country.id) && Objects.equals(name, country.name); } @Override public int hashCode() { return Objects.hash(id, name, population); } @Override public String toString() { final StringBuilder sb = new StringBuilder("Country{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append(", population=").append(population); sb.append('}'); return sb.toString(); } } ``` 這是`Country`實體。 每個實體必須至少定義兩個注解:`@Entity`和`@Id`。 以前,我們將`ddl-auto`選項設置為`create-drop`,這意味著 Hibernate 將根據該實體創建表模式。 ```java @Entity @Table(name = "countries") public class Country { ``` `@Entity`注解指定該類是一個實體,并映射到數據庫表。 `@Table`注解指定要用于映射的數據庫表的名稱。 ```java @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; ``` `@Id`注解指定實體的主鍵,`@GeneratedValue`給出主鍵值的生成策略。 `com/zetcode/repository/CountryRepository.java` ```java package com.zetcode.repository; import com.zetcode.bean.Country; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CountryRepository extends CrudRepository<Country, Long> { } ``` `CountryRepository`用`@Repository`注解修飾。 通過從 Spring `CrudRepository`擴展,我們為數據庫實現了一些方法,包括`findAll()`。 這樣可以節省一些樣板代碼。 `com/zetcode/service/ICountryService.java` ```java package com.zetcode.service; import com.zetcode.bean.Country; import java.util.List; public interface ICountryService { public List<Country> findAll(); } ``` `ICountryService`包含`findAll()`契約方法。 `com/zetcode/service/CountryService.java` ```java package com.zetcode.service; import com.zetcode.model.Country; import com.zetcode.repository.CountryRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CountryService implements ICountryService { @Autowired private CountryRepository repository; @Override public List<Country> findAll() { var countries = (List<Country>) repository.findAll(); return countries; } } ``` `CountryService`包含`findAll()`方法的實現。 ```java @Autowired private CountryRepository repository; ``` `CountryRepository`注入了`@Autowired`注解。 ```java @Override public List<Country> findAll() { var countries = (List<Country>) repository.findAll(); return countries; } ``` `findAll()`方法從數據庫返回所有國家的列表。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import com.zetcode.model.Country; import com.zetcode.service.ICountryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.List; @Controller public class MyController { @Autowired ICountryService countryService; @RequestMapping("/showCountries") public ModelAndView findCities() { var countries = (List<Country>) countryService.findAll(); var params = new HashMap<String, Object>(); params.put("countries", countries); return new ModelAndView("showCountries", params); } } ``` `MyController`處理來自客戶端的請求。 ```java @Controller public class MyController { ``` 控制器帶有`@Controller`注解。 ```java @Autowired ICountryService countryService; ``` `ICountryService`注入到`countryService`字段中。 ```java var countries = (List<Country>) countryService.findAll(); ``` 從服務對象中,我們使用`findAll()`方法檢索所有國家。 ```java var params = new HashMap<String, Object>(); params.put("countries", countries); return new ModelAndView("showCountries", params); ``` 處理和國家列表一起發送到`showCountries.ftl`模板文件。 我們已經在 Maven POM 文件中提供了 Freemarker 依賴項; 因此,Spring Boot 會找出視圖的擴展名。 `resources/static/index.html` ```java <!DOCTYPE html> <html> <head> <title>Home page</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p> <a href="showCountries">Show countries</a> </p> </body> </html> ``` 這是主頁。 它包含一個獲取所有國家的鏈接。 `resources/templates/showCountries.ftl` ```java <!DOCTYPE html> <html> <head> <title>Show countries</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>List of countries</h2> <table> <tr> <th>Id</th> <th>Name</th> <th>Population</th> </tr> <#list countries as country> <tr> <td>${country.id}</td> <td>${country.name}</td> <td>${country.population}</td> </tr> </#list> </table> </body> </html> ``` 這是`showCountries.ftl`模板文件。 使用`#list`指令,我們顯示列表中的所有項目。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`是設置 Spring Boot 應用的入口。 `@SpringBootApplication`注解啟用自動配置和組件掃描。 它是`@Configuration`,`@EnableAutoConfiguration`和`@ComponentScan`注解的便捷注解。 ```java $ mvn -q spring-boot:run ``` 我們運行該應用。 在本教程中,我們展示了如何在 Spring 應用中使用`@Repository`注解。 您可能也對相關教程感興趣: [Spring Boot `@Controller`教程](/springboot/controller/), [Spring Boot `@RequestParam`教程](/springboot/requestparam/)和 [Java 教程](/lang/java/),或列出[全部 Spring Boot 教程](/all/#springboot)。
                  <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>

                              哎呀哎呀视频在线观看