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

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring Boot PostgreSQL 教程 > 原文: [http://zetcode.com/springboot/postgresql/](http://zetcode.com/springboot/postgresql/) Spring Boot PostgreSQL 教程展示了如何在 Spring Boot 應用中使用 PostgreSQL 數據庫。 Spring 是用于創建企業應用的流行 Java 應用框架。 Spring Boot 是 Spring 框架的演進,可幫助您輕松創建獨立的,生產級的基于 Spring 的應用。 ## PostgreSQL PostgreSQL 是一個功能強大的開源對象關系數據庫系統。 它是一個多用戶數據庫管理系統。 它可以在包括 Linux,FreeBSD,Solaris,Microsoft Windows 和 Mac OSX 在內的多個平臺上運行。PostgreSQL 由 PostgreSQL 全球開發小組開發。 ## PostgreSQL 設置 我們將展示如何在 Debian Linux 系統上安裝 PostgreSQL 數據庫。 ```java $ sudo apt-get install postgresql ``` 此命令將安裝 PostgreSQL 服務器和相關包。 ```java $ /etc/init.d/postgresql status ``` 我們使用`postgresql status`命令檢查數據庫的狀態。 ```java $ sudo -u postgres psql postgres psql (9.5.10) Type "help" for help. postgres=# \password postgres Enter new password: Enter it again: ``` 安裝后,將使用空的默認密碼創建一個具有管理權限的`postgres`用戶。 第一步,我們需要為`postgres`設置密碼。 ```java $ sudo -u postgres createuser --interactive --password user12 Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) y Shall the new role be allowed to create more new roles? (y/n) n Password: ``` 我們創建一個新的數據庫用戶。 ```java $ sudo -u postgres createdb testdb -O user12 ``` 我們使用`createdb`命令創建一個新的`testdb`數據庫,該數據庫將由`user12`擁有。 ```java $ sudo vi /etc/postgresql/9.5/main/pg_hba.conf ``` 我們編輯`pg_hba.conf`文件。 ```java # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust ``` 為了能夠在本地 PostgreSQL 安裝中運行 Spring Boot 應用,我們將 Unix 域套接字和本地連接的認證方法更改為`trust`。 ```java $ sudo service postgresql restart ``` 我們重新啟動 PostgreSQL 以啟用更改。 ```java $ psql -U user12 -d testdb -W Password for user user12: psql (9.5.10) Type "help" for help. testdb=> ``` 現在我們可以使用`psql`工具連接到數據庫。 ## Spring Boot PostgreSQL 示例 以下應用是一個簡單的 Spring Boot Web 應用,它使用 PostgreSQL 數據庫。 我們有一個主頁,帶有一個鏈接,用于顯示數據庫表中的數據。 我們使用 Thymeleaf 模板系統將數據與 HTML 連接。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ ├───controller │ │ │ MyController.java │ │ ├───model │ │ │ City.java │ │ ├───repository │ │ │ CityRepository.java │ │ └───service │ │ CityService.java │ │ ICityService.java │ └───resources │ │ application.properties │ │ data-postgres.sql │ │ schema-postgres.sql │ ├───static │ │ index.html │ └───templates │ showCities.html └───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>springbootpostgreex</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.7.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</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> ``` Spring Boot 啟動器是一組方便的依賴項描述符,可以極大地簡化 Maven 配置。 `spring-boot-starter-parent`具有 Spring Boot 應用的一些常用配置。 `spring-boot-starter-web`是使用 Spring MVC 構建 Web(包括 RESTful)應用的入門工具。 它使用 Tomcat 作為默認的嵌入式容器。 `spring-boot-starter-thymeleaf`是使用 Thymeleaf 視圖構建 MVC Web 應用的入門工具。 `spring-boot-starter-data-jpa`是將 Spring Data JPA 與 Hibernate 結合使用的入門工具。 `postgresql`依賴項適用于 PostgreSQL 數據庫驅動程序。 在`spring-boot-maven-plugin`提供了 Maven 的 Spring Boot 支持,使我們能夠打包可執行的 JAR 或 WAR 檔案。 它的`spring-boot:run`目標運行 Spring Boot 應用。 `resources/application.properties` ```java spring.main.banner-mode=off logging.level.org.springframework=ERROR spring.jpa.hibernate.ddl-auto=none spring.datasource.initialization-mode=always spring.datasource.platform=postgres spring.datasource.url=jdbc:postgresql://localhost:5432/testdb spring.datasource.username=postgres spring.datasource.password=s$cret spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true ``` 在`application.properties`文件中,我們編寫了 Spring Boot 應用的各種配置設置。 使用`spring.main.banner-mode`屬性,我們可以關閉 Spring 橫幅。 要加載未嵌入的數據庫,在 Spring Boot 2 中,我們需要添加`spring.datasource.initialization-mode=always`。 為避免沖突,我們使用`spring.jpa.hibernate.ddl-auto=none`關閉自動模式創建。 在 spring 數據源屬性中,我們設置了 PostgreSQL 數據源。 設置`spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation`選項可以避免最近發生的問題。 沒有此選項,我們將收到以下錯誤: ```java java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented. ``` `com/zetcode/model/City.java` ```java package com.zetcode.model; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "cities") public class City { @Id @GeneratedValue(strategy = GenerationType.AUTO) 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 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 int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.id); hash = 79 * hash + Objects.hashCode(this.name); hash = 79 * hash + this.population; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final City other = (City) obj; if (this.population != other.population) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return Objects.equals(this.id, other.id); } @Override public String toString() { final StringBuilder sb = new StringBuilder("City{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append(", population=").append(population); sb.append('}'); return sb.toString(); } } ``` 這是`City`實體。 每個實體必須至少定義兩個注解:`@Entity`和`@Id`。 ```java @Entity @Table(name = "cities") public class City { ``` `@Entity`注解指定該類是一個實體,并映射到數據庫表。 `@Table`注解指定要用于映射的數據庫表的名稱。 ```java @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; ``` `@Id`注解指定實體的主鍵,`@GeneratedValue`提供規范主鍵值的生成策略。 `resources/schema-postgres.sql` ```java DROP TABLE IF EXISTS cities; CREATE TABLE cities(id serial PRIMARY KEY, name VARCHAR(255), population integer); ``` 啟動應用后,如果關閉了自動模式創建,則將執行`schema-postgres.sql`腳本。 該腳本將創建一個新的數據庫表。 `resources/data-postgres.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); ``` 之后,執行`data-postgres.sql`文件以用數據填充表。 `com/zetcode/repository/CityRepository.java` ```java package com.zetcode.repository; import com.zetcode.model.City; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CityRepository extends CrudRepository<City, Long> { } ``` 通過從 Spring `CrudRepository`擴展,我們將為我們的數據存儲庫實現一些方法,包括`findAll()`。 這樣,我們節省了大量樣板代碼。 `com/zetcode/service/ICityService.java` ```java package com.zetcode.service; import com.zetcode.model.City; import java.util.List; public interface ICityService { List<City> findAll(); } ``` `ICityService`提供了一種從數據源獲取所有城市的契約方法。 `com/zetcode/service/CityService.java` ```java package com.zetcode.service; import com.zetcode.model.City; import com.zetcode.repository.CityRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CityService implements ICityService { @Autowired private CityRepository repository; @Override public List<City> findAll() { var cities = (List<City>) repository.findAll(); return cities; } } ``` `CityService`包含`findAll()`方法的實現。 我們使用存儲庫從數據庫檢索數據。 ```java @Autowired private CityRepository repository; ``` 注入`CityRepository`。 ```java var cities = (List<City>) repository.findAll(); ``` 存儲庫的`findAll()`方法返回城市列表。 `com/zetcode/MyController.java` ```java package com.zetcode.controller; import com.zetcode.model.City; import com.zetcode.service.ICityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class MyController { @Autowired private ICityService cityService; @GetMapping("/showCities") public String findCities(Model model) { var cities = (List<City>) cityService.findAll(); model.addAttribute("cities", cities); return "showCities"; } } ``` `MyController`包含一個映射。 ```java @Autowired private ICityService cityService; ``` 我們在`countryService`字段中插入`ICityService`。 ```java @GetMapping("/showCities") public String findCities(Model model) { var cities = (List<City>) cityService.findAll(); model.addAttribute("cities", cities); return "showCities"; } ``` 我們將帶有`showCities`路徑的請求映射到控制器的`findCities()`方法。 默認請求是 GET 請求。 該模型將獲取城市列表,并將處理過程發送到`showCities.html` Thymeleaf 模板文件。 `resources/templates/showCities.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Cities</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>List of cities</h2> <table> <tr> <th>Id</th> <th>Name</th> <th>Population</th> </tr> <tr th:each="city : ${cities}"> <td th:text="${city.id}">Id</td> <td th:text="${city.name}">Name</td> <td th:text="${city.population}">Population</td> </tr> </table> </body> </html> ``` 在`showCities.html`模板文件中,我們在 HTML 表中顯示數據。 `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> <a href="showCities">Show cities</a> </body> </html> ``` `index.html`中有一個鏈接,顯示所有城市。 `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`啟用自動配置和組件掃描。 ```java $ mvn spring-boot:run ``` 應用運行后,我們可以導航到`localhost:8080`。 在本教程中,我們展示了如何在 Spring Boot 應用中使用 PostgreSQL 數據庫。 您可能也對相關教程感興趣: * [Spring Boot MySQL 教程](/springboot/mysql/) * [Spring Boot H2 REST 教程](/articles/springbootresth2/) * [Spring Boot Thymeleaf 教程](/articles/springbootthymeleaf/) * [Spring Web 應用介紹](/articles/springwebfirst/) * [Spring Boot RESTFul 應用](/articles/springbootrestsimple/) 查找[所有 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>

                              哎呀哎呀视频在线观看