<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 Hibernate 配置示例 > 原文: [https://howtodoinjava.com/spring-boot2/hibernate-configuration-example/](https://howtodoinjava.com/spring-boot2/hibernate-configuration-example/) 學習在 [Spring Boot2](https://howtodoinjava.com/spring-boot-tutorials/) 應用程序中配置 [Hibernate](https://howtodoinjava.com/hibernate-tutorials/) / JPA 支持,以及創建實體類和擴展內置的`JpaRepository`接口。 ## 1\. Maven 依賴 在此示例中,我們使用 maven 在項目中添加運行時 jar。 如果您使用 gradle,請查找相關的依賴項。 `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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.howtodoinjava.demo</groupId> <artifactId>SpringBoot2Demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBoot2Demo</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-web</artifactId> </dependency> <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> ``` * `spring-boot-starter-data-jpa`(必填):它包含 spring 數據,hibernate,HikariCP, [JPA API](https://howtodoinjava.com/jpa-tutorials-and-examples/),**JPA 實現(默認以 Hibernate 實現)**,JDBC 和其他必需的庫。 * `h2`:盡管我們可以使用`application.properties`文件中的數據源屬性輕松添加任何數據庫,但我們正在使用[ h2 數據庫](https://howtodoinjava.com/spring-boot2/h2-database-example/)來減少不必要的復雜性。 ## 2\. 創建 JPA 實體類 在類路徑中包含必需的 jar 之后,根據項目需要創建幾個實體類。 例如,我們在這里創建一個這樣的實體`EmployeeEntity`。 請記住,僅包含 JPA API 注解(`javax.persistence.*`)可使 Hibernate 與應用程序代碼脫鉤。 `EmployeeEntity.java` ```java import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="TBL_EMPLOYEES") public class EmployeeEntity { @Id @GeneratedValue private Long id; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; @Column(name="email", nullable=false, length=200) private String email; //Setters and getters left out for brevity. @Override public String toString() { return "EmployeeEntity [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } } ``` * 我們無需執行任何操作即可使此類可掃描。 Spring Boot 將查找所有`@Entity`注解的類,并將它們默認配置為 JPA 實體。 * 默認情況下,表格的名稱是實體類的名稱,例如在上述情況下,應為`EmployeeEntity`。 我們可以使用`@Table`注解及其`name`屬性來自定義表格名稱。 * `id`屬性帶有`@Id`注解,因此 JPA 會將其識別為對象的 ID。 同樣,`@GeneratedValue`注解啟用其自動生成的值。 * 要自定義列的名稱,允許使用`null`值或列大小等,請使用`@Column`注解。 * 我建議重寫`toString()`方法以在日志中打印員工的基本詳細信息。 > 閱讀更多: [JPA 注解](https://howtodoinjava.com/hibernate/hibernate-jpa-2-persistence-annotations-tutorial/) ## 3\. 創建 JPA 存儲庫 擴展[`JpaRepository`](https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html)接口,以允許在運行時為任何給定的實體類自動創建存儲庫實現。 實體類別的類型及其 ID 字段在`JpaRepository`的通用參數中指定。 `EmployeeRepository.java` ```java import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.howtodoinjava.demo.entity.EmployeeEntity; @Repository public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long> { } ``` 通過此簡單擴展,`EmployeeRepository`繼承了用于處理`Employee`持久性的幾種方法,包括保存,刪除和查找`Employee`實體的方法。 除了提供的默認方法外,我們還可以向此接口添加我們自己的自定義方法和查詢。 ## 4\. 屬性配置 #### 4.1. 數據源 在`application.properties`文件中提供數據源連接屬性,這將有助于將數據庫連接到 JPA 代碼。 在給定的配置中,我們正在配置 h2 數據庫。 `application.properties` ```java spring.datasource.url=jdbc:h2:file:~/test spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # Enabling H2 Console spring.h2.console.enabled=true # Custom H2 Console URL spring.h2.console.path=/h2-console ``` #### 4.2. Hibernate 打印 SQL 和日志記錄 查看組件如何工作的一個好方法是啟用大量日志記錄。 僅在很少的屬性條目下進行操作即可。 `application.properties` ```java #Turn Statistics on and log SQL stmts spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true #If want to see very extensive logging spring.jpa.properties.hibernate.generate_statistics=true logging.level.org.hibernate.type=trace logging.level.org.hibernate.stat=debug ``` #### 4.3. 數據庫初始化 在基于 JPA 的應用程序中,我們可以選擇讓 Hibernate 使用實體類創建架構,也可以使用`schema.sql`,但是我們不能兩者都做。 如果使用`schema.sql`,請確保禁用`spring.jpa.hibernate.ddl-auto`。 `application.properties` ```java #Schema will be created using schema.sql and data.sql files spring.jpa.hibernate.ddl-auto=none ``` `schama.sql` ```java DROP TABLE IF EXISTS TBL_EMPLOYEES; CREATE TABLE TBL_EMPLOYEES ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(250) NOT NULL, last_name VARCHAR(250) NOT NULL, email VARCHAR(250) DEFAULT NULL ); ``` `data.sql` ```java INSERT INTO TBL_EMPLOYEES (first_name, last_name, email) VALUES ('Lokesh', 'Gupta', 'abc@gmail.com'), ('Deja', 'Vu', 'xyz@email.com'), ('Caption', 'America', 'cap@marvel.com'); ``` ## 5\. Spring Boot Hibernate 演示 要使用 Spring Boot 測試 Hibernate 配置,我們需要在類中自動裝配`EmployeeRepository`依賴項,并使用其方法保存或獲取員工實體。 讓我們在`@SpringBootApplication`帶注解的類中并使用[`CommandLineRunner`](https://howtodoinjava.com/spring-boot/command-line-runner-interface-example/)接口進行此測試。 應用程序啟動后立即執行`CommandLineRunner`中的`run()`方法。 `SpringBoot2DemoApplication.java` ```java package com.howtodoinjava.demo; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.howtodoinjava.demo.entity.EmployeeEntity; import com.howtodoinjava.demo.repository.EmployeeRepository; @SpringBootApplication public class SpringBoot2DemoApplication implements CommandLineRunner { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired EmployeeRepository repository; public static void main(String[] args) { SpringApplication.run(SpringBoot2DemoApplication.class, args); } @Override public void run(String... args) throws Exception { Optional<EmployeeEntity> emp = repository.findById(2L); logger.info("Employee id 2 -> {}", emp.get()); } } ``` 運行該應用程序并觀察輸出。 請注意,要在日志中打印有限的信息,我在應用程序中使用屬性`logging.pattern.console=&m%n` `Console` ```java Tomcat initialized with port(s): 8080 (http) Starting service [Tomcat] Starting Servlet engine: [Apache Tomcat/9.0.19] Initializing Spring embedded WebApplicationContext Root WebApplicationContext: initialization completed in 5748 ms HikariPool-1 - Starting... HikariPool-1 - Start completed. HHH000204: Processing PersistenceUnitInfo [ name: default ...] HHH000412: Hibernate Core {5.3.10.Final} HHH000206: hibernate.properties not found HCANN000001: Hibernate Commons Annotations {5.0.4.Final} HHH000400: Using dialect: org.hibernate.dialect.H2Dialect Initialized JPA EntityManagerFactory for persistence unit 'default' Initializing ExecutorService 'applicationTaskExecutor' spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning Tomcat started on port(s): 8080 (http) with context path '' Started SpringBoot2DemoApplication in 17.638 seconds (JVM running for 19.1) Hibernate: select employeeen0_.id as id1_0_0_, employeeen0_.email as email2_0_0_, employeeen0_.first_name as first_na3_0_0_, employeeen0_.last_name as last_nam4_0_0_ from tbl_employees employeeen0_ where employeeen0_.id=? Employee id 2 -> EmployeeEntity [id=2, firstName=Deja, lastName=Vu, email=xyz@email.com] ``` 顯然,已經配置了 Hibernate 模式,并且我們能夠使用 JPA 存儲庫接口與數據庫進行交互。 將我的問題留在 **Spring Boot 和配置 Hibernate** 有關的評論部分。 ## 6\. Spring Boot Hibernate 教程 1. [使用 Hibernate 的 Spring boot crud 操作示例](https://howtodoinjava.com/spring-boot2/spring-boot-crud-hibernate/) 2. [使用 Thymeleaf 和 Hibernate 的 Spring Boot CRUD 應用程序](https://howtodoinjava.com/spring-boot2/crud-application-thymeleaf/) 3. [Spring Boot 分頁和排序示例](https://howtodoinjava.com/spring-boot2/pagination-sorting-example/) 學習愉快! [下載源碼](https://howtodoinjava.com/wp-content/downloads/spring-boot-hibernate-crud-demo.zip)
                  <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>

                              哎呀哎呀视频在线观看