<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Spring Boot H2 REST 教程 > 原文: [http://zetcode.com/articles/springbootresth2/](http://zetcode.com/articles/springbootresth2/) 在本教程中,我們將使用 H2 數據庫創建一個簡單的 Spring Boot RESTful 應用。 Spring 是用于創建企業應用的流行 Java 應用框架。 Spring Boot 是一種以最少的精力創建獨立的,基于生產級別的基于 Spring 的應用的方法。 Apache Tomcat 是由 Apache 軟件基金會(ASF)開發的開源 Java Servlet 容器。 Tomcat 實現了幾種 Java EE 規范,包括 Java Servlet,JavaServer Pages(JSP),Java EL 和 WebSocket。 Tomcat 可以獨立和嵌入式模式運行。 H2 是完全用 Java 創建的開源關系數據庫管理系統。 它可以嵌入 Java 應用中或以客戶端-服務器模式運行。 它易于部署和安裝,占地面積小。 `JdbcTemplate`是一個 Spring 庫,可以幫助程序員創建與關系數據庫和 JDBC 一起使用的應用。 它會處理許多繁瑣且容易出錯的底層細節,例如處理事務,清理資源以及正確處理異常。 `JdbcTemplate`在 Spring 的`spring-jdbc`模塊中提供。 JSON(JavaScript 對象表示法)是一種輕量級的數據交換格式。 人類可以輕松地進行讀寫,并通過機器解析并生成 JSON。 JSON 的官方互聯網媒體類型為`application/json`。 JSON 文件擴展名是`.json`。 RESTFul 應用遵循 REST 架構樣式,該樣式用于設計網絡應用。 RESTful 應用生成 HTTP 請求,這些請求對資源執行 CRUD(創建/讀取/更新/刪除)操作。 ## 應用 我們的應用是一個運行在嵌入式 Tomcat 服務器上的 Spring Boot RESTful 應用。 它以 JSON 格式從 H2 數據庫返回數據。 該應用使用`JdbcTemplate`簡化 JDBC 編程。 ```java $ tree . ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── Application.java │ │ ├── bean │ │ │ └── City.java │ │ ├── controller │ │ │ └── MyController.java │ │ └── service │ │ ├── CityService.java │ │ └── ICityService.java │ └── resources │ ├── application.yml │ ├── data-h2.sql │ └── schema-h2.sql └── 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>SpringBootRestH2</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.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-jdbc</artifactId> </dependency> </dependencies> </project> ``` 這是 Maven 構建文件。 `h2`依賴項是 H2 數據庫的驅動程序。 `spring-boot-devtools`啟用熱插拔,禁用模板緩存并啟用實時重載。 `spring-boot-starter-web`是使用 Spring MVC 構建 Web(包括 RESTful)應用的入門程序。 `spring-boot-starter-jdbc`是在 Spring Boot 中使用 JDBC 的入門工具。 `application.yml` ```java server: port: 8086 context-path: /rest spring: main: banner-mode: "off" datasource: platform: h2 driverClassName: org.h2.Driver url: jdbc:h2:mem:test;MODE=PostgreSQL logging: level: org: springframework: ERROR ``` `application.yml`文件包含 Spring Boot 應用的各種配置設置。 我們具有服務器端口和上下文路徑(應用名稱)的映射。 使用`banner-mode`屬性,我們可以關閉 Spring 橫幅。 該平臺值用在 SQL 初始化腳本中:`schema-${platform}.sql`和`data-${platform}.sql`。 我們將 H2 設置為使用 PostgreSQL 兼容模式。 H2 數據庫在內存中運行。 另外,我們將 spring 框架的日志記錄級別設置為`ERROR`。 該文件位于`src/main/resources`目錄中。 `City.java` ```java package com.zetcode.bean; public class City { private Long id; private String name; private int population; public City() { } public City(Long id, String name, int population) { this.id = id; this.name = name; this.population = population; } public Long getId() { return id; } public void setId(Long id) { this.id = 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 String toString() { return "City{" + "id=" + id + ", name=" + name + ", population=" + population + '}'; } } ``` 這是`City` bean。 `schema-h2.sql` ```java CREATE TABLE CITIES(ID BIGINT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(30), POPULATION BIGINT); ``` 該 SQL 腳本創建`CITIES`表。 `data-h2.sql` ```java INSERT INTO CITIES(NAME, POPULATION) VALUES('Bratislava', 432000); INSERT INTO CITIES(NAME, POPULATION) VALUES('Budapest', 1759000); INSERT INTO CITIES(NAME, POPULATION) VALUES('Prague', 1280000); INSERT INTO CITIES(NAME, POPULATION) VALUES('Warsaw', 1748000); INSERT INTO CITIES(NAME, POPULATION) VALUES('Los Angeles', 3971000); INSERT INTO CITIES(NAME, POPULATION) VALUES('New York', 8550000); INSERT INTO CITIES(NAME, POPULATION) VALUES('Edinburgh', 464000); INSERT INTO CITIES(NAME, POPULATION) VALUES('Berlin', 3671000); ``` 該腳本用數據填充表。 這兩個腳本都位于類路徑的根目錄中。 `ICityService.java` ```java package com.zetcode.service; import com.zetcode.bean.City; import java.util.List; public interface ICityService { public List<City> findAll(); public City findById(Long id); } ``` `ICityService`提供了獲取所有城市并通過其 ID 從數據源獲取城市的契約方法。 `CityService.java` ```java package com.zetcode.service; import com.zetcode.bean.City; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service public class CityService implements ICityService { @Autowired private JdbcTemplate jtm; @Override public List<City> findAll() { String sql = "SELECT * FROM CITIES"; List<City> cities = jtm.query(sql, new BeanPropertyRowMapper(City.class)); return cities; } @Override public City findById(Long id) { String sql = "SELECT * FROM CITIES WHERE ID=?"; City city = (City) jtm.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper(City.class)); return city; } } ``` `CityService`包含`findAll()`和`findById()`方法的實現。 我們使用 Spring 的`JdbcTemplate`來執行 SQL 代碼。 ```java @Autowired private JdbcTemplate jtm; ``` 注入`JdbcTemplate`。 ```java String sql = "SELECT * FROM CITIES"; ``` 這是從`CITIES`表中選擇所有城市的 SQL。 ```java List<City> cities = jtm.query(sql, new BeanPropertyRowMapper(City.class)); ``` `BeanPropertyRowMapper`將一行轉換為指定映射目標類的新實例。 ```java String sql = "SELECT * FROM CITIES WHERE ID=?"; ``` 這是用于從`CITIES`表中選擇由 ID 標識的特定城市的 SQL。 ```java City city = (City) jtm.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper(City.class)); ``` 要從`CITIES`表中獲得一行,我們使用`queryForObject()`方法。 `MyController.java` ```java package com.zetcode.controller; import com.zetcode.bean.City; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import com.zetcode.service.ICityService; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private ICityService cityService; @RequestMapping("/cities") public List<City> findCities() { return cityService.findAll(); } @RequestMapping("/cities/{userId}") public City findCity(@PathVariable Long userId) { return cityService.findById(userId); } } ``` 這是 Spring Boot RESTful 應用的控制器類。 `@RestController`注解創建一個 RESTful 控制器。 傳統的 MVC 控制器使用`ModelAndView`,而 RESTful 控制器僅返回對象,并且對象數據以 JSON 或 XML 格式直接寫入 HTTP 響應。 ```java @Autowired private ICityService cityService; ``` 我們在`countryService`字段中插入`ICityService`。 ```java @RequestMapping("/cities") public List<City> findCities() { return cityService.findAll(); } ``` `@RequestMapping`注解用于將 Web 請求映射到 Spring 控制器方法。 在這里,我們將具有`/cities`路徑的請求映射到控制器的`findCities()`方法。 默認請求是 GET 請求。 我們不需要手動將`City`域對象轉換為 JSON。 因為 Jackson 2 在類路徑中((通過`spring-boot-starter-web`包含在內),所以 Spring 會自動選擇`MappingJackson2HttpMessageConverter`將`City`實例轉換為 JSON。 `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`啟用自動配置和組件掃描。 ```java $ mvn spring-boot:run ``` 使用`mvn spring-boot:run`命令,運行應用。 該應用部署在嵌入式 Tomcat 服務器上。 ```java $ curl localhost:8086/rest/cities [{"id":1,"name":"Bratislava","population":432000},{"id":2,"name":"Budapest","population":1759000}, {"id":3,"name":"Prague","population":1280000},{"id":4,"name":"Warsaw","population":1748000}, {"id":5,"name":"Los Angeles","population":3971000},{"id":6,"name":"New York","population":8550000}, {"id":7,"name":"Edinburgh","population":464000},{"id":8,"name":"Berlin","population":3671000}] ``` 使用`curl`命令,我們可以獲得所有城市。 ```java $ curl localhost:8086/rest/cities/1 {"id":1,"name":"Bratislava","population":432000} ``` 在這里,我們得到了一個由其 ID 標識的城市。 在本教程中,我們創建了一個 Spring Boot RESTful 應用,該應用以 JSON 格式從 H2 數據庫返回數據。 您可能也對相關教程感興趣: [Spring Boot Thymeleaf 教程](/articles/springbootthymeleaf/), [Spring Boot Mustache 教程](/articles/springbootmustache/), [Spring Boot Swing 集成教程](/articles/springbootswing/), [Spring 傳統的 Spring 應用簡介](/articles/springwebfirst/)中的 Web 應用, [Spring Boot RESTFul 應用](/articles/springbootrestsimple/),[`JdbcTemplate`](/articles/springjdbctemplate/)。
                  <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>

                              哎呀哎呀视频在线观看