原文: https://howtodoinjava.com/spring-boot2/hibernate-configuration-example/

学习在 Spring Boot2 应用程序中配置 Hibernate / JPA 支持,以及创建实体类和扩展内置的JpaRepository接口。

1. Maven 依赖

在此示例中,我们使用 maven 在项目中添加运行时 jar。 如果您使用 gradle,请查找相关的依赖项。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <parent>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-parent</artifactId>
  10. <version>2.1.5.RELEASE</version>
  11. <relativePath /> <!-- lookup parent from repository -->
  12. </parent>
  13. <groupId>com.howtodoinjava.demo</groupId>
  14. <artifactId>SpringBoot2Demo</artifactId>
  15. <version>0.0.1-SNAPSHOT</version>
  16. <name>SpringBoot2Demo</name>
  17. <description>Demo project for Spring Boot</description>
  18. <properties>
  19. <java.version>1.8</java.version>
  20. </properties>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-data-jpa</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>com.h2database</groupId>
  32. <artifactId>h2</artifactId>
  33. <scope>runtime</scope>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-test</artifactId>
  38. <scope>test</scope>
  39. </dependency>
  40. </dependencies>
  41. <build>
  42. <plugins>
  43. <plugin>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-maven-plugin</artifactId>
  46. </plugin>
  47. </plugins>
  48. </build>
  49. </project>
  • spring-boot-starter-data-jpa(必填):它包含 spring 数据,hibernate,HikariCP, JPA APIJPA 实现(默认以 Hibernate 实现),JDBC 和其他必需的库。
  • h2:尽管我们可以使用application.properties文件中的数据源属性轻松添加任何数据库,但我们正在使用 h2 数据库来减少不必要的复杂性。

2. 创建 JPA 实体类

在类路径中包含必需的 jar 之后,根据项目需要创建几个实体类。 例如,我们在这里创建一个这样的实体EmployeeEntity

请记住,仅包含 JPA API 注解(javax.persistence.*)可使 Hibernate 与应用程序代码脱钩。

EmployeeEntity.java

  1. import javax.persistence.Column;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.Id;
  5. import javax.persistence.Table;
  6. @Entity
  7. @Table(name="TBL_EMPLOYEES")
  8. public class EmployeeEntity {
  9. @Id
  10. @GeneratedValue
  11. private Long id;
  12. @Column(name="first_name")
  13. private String firstName;
  14. @Column(name="last_name")
  15. private String lastName;
  16. @Column(name="email", nullable=false, length=200)
  17. private String email;
  18. //Setters and getters left out for brevity.
  19. @Override
  20. public String toString() {
  21. return "EmployeeEntity [id=" + id + ", firstName=" + firstName +
  22. ", lastName=" + lastName + ", email=" + email + "]";
  23. }
  24. }
  • 我们无需执行任何操作即可使此类可扫描。 Spring Boot 将查找所有@Entity注解的类,并将它们默认配置为 JPA 实体。
  • 默认情况下,表格的名称是实体类的名称,例如在上述情况下,应为EmployeeEntity。 我们可以使用@Table注解及其name属性来自定义表格名称。
  • id属性带有@Id注解,因此 JPA 会将其识别为对象的 ID。 同样,@GeneratedValue注解启用其自动生成的值。
  • 要自定义列的名称,允许使用null值或列大小等,请使用@Column注解。
  • 我建议重写toString()方法以在日志中打印员工的基本详细信息。

阅读更多: JPA 注解

3. 创建 JPA 存储库

扩展JpaRepository接口,以允许在运行时为任何给定的实体类自动创建存储库实现。 实体类别的类型及其 ID 字段在JpaRepository的通用参数中指定。

EmployeeRepository.java

  1. import org.springframework.data.jpa.repository.JpaRepository;
  2. import org.springframework.stereotype.Repository;
  3. import com.howtodoinjava.demo.entity.EmployeeEntity;
  4. @Repository
  5. public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long> {
  6. }

通过此简单扩展,EmployeeRepository继承了用于处理Employee持久性的几种方法,包括保存,删除和查找Employee实体的方法。

除了提供的默认方法外,我们还可以向此接口添加我们自己的自定义方法和查询。

4. 属性配置

4.1. 数据源

application.properties文件中提供数据源连接属性,这将有助于将数据库连接到 JPA 代码。

在给定的配置中,我们正在配置 h2 数据库。

application.properties

  1. spring.datasource.url=jdbc:h2:file:~/test
  2. spring.datasource.driverClassName=org.h2.Driver
  3. spring.datasource.username=sa
  4. spring.datasource.password=
  5. spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
  6. # Enabling H2 Console
  7. spring.h2.console.enabled=true
  8. # Custom H2 Console URL
  9. spring.h2.console.path=/h2-console

4.2. Hibernate 打印 SQL 和日志记录

查看组件如何工作的一个好方法是启用大量日志记录。 仅在很少的属性条目下进行操作即可。

application.properties

  1. #Turn Statistics on and log SQL stmts
  2. spring.jpa.show-sql=true
  3. spring.jpa.properties.hibernate.format_sql=true
  4. #If want to see very extensive logging
  5. spring.jpa.properties.hibernate.generate_statistics=true
  6. logging.level.org.hibernate.type=trace
  7. logging.level.org.hibernate.stat=debug

4.3. 数据库初始化

在基于 JPA 的应用程序中,我们可以选择让 Hibernate 使用实体类创建架构,也可以使用schema.sql,但是我们不能两者都做。

如果使用schema.sql,请确保禁用spring.jpa.hibernate.ddl-auto

application.properties

  1. #Schema will be created using schema.sql and data.sql files
  2. spring.jpa.hibernate.ddl-auto=none

schama.sql

  1. DROP TABLE IF EXISTS TBL_EMPLOYEES;
  2. CREATE TABLE TBL_EMPLOYEES (
  3. id INT AUTO_INCREMENT PRIMARY KEY,
  4. first_name VARCHAR(250) NOT NULL,
  5. last_name VARCHAR(250) NOT NULL,
  6. email VARCHAR(250) DEFAULT NULL
  7. );

data.sql

  1. INSERT INTO TBL_EMPLOYEES
  2. (first_name, last_name, email)
  3. VALUES
  4. ('Lokesh', 'Gupta', 'abc@gmail.com'),
  5. ('Deja', 'Vu', 'xyz@email.com'),
  6. ('Caption', 'America', 'cap@marvel.com');

5. Spring Boot Hibernate 演示

要使用 Spring Boot 测试 Hibernate 配置,我们需要在类中自动装配EmployeeRepository依赖项,并使用其方法保存或获取员工实体。

让我们在@SpringBootApplication带注解的类中并使用CommandLineRunner接口进行此测试。 应用程序启动后立即执行CommandLineRunner中的run()方法。

SpringBoot2DemoApplication.java

  1. package com.howtodoinjava.demo;
  2. import java.util.Optional;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.boot.SpringApplication;
  8. import org.springframework.boot.autoconfigure.SpringBootApplication;
  9. import com.howtodoinjava.demo.entity.EmployeeEntity;
  10. import com.howtodoinjava.demo.repository.EmployeeRepository;
  11. @SpringBootApplication
  12. public class SpringBoot2DemoApplication implements CommandLineRunner {
  13. private Logger logger = LoggerFactory.getLogger(this.getClass());
  14. @Autowired
  15. EmployeeRepository repository;
  16. public static void main(String[] args) {
  17. SpringApplication.run(SpringBoot2DemoApplication.class, args);
  18. }
  19. @Override
  20. public void run(String... args) throws Exception
  21. {
  22. Optional<EmployeeEntity> emp = repository.findById(2L);
  23. logger.info("Employee id 2 -> {}", emp.get());
  24. }
  25. }

运行该应用程序并观察输出。 请注意,要在日志中打印有限的信息,我在应用程序中使用属性logging.pattern.console=&m%n

Console

  1. Tomcat initialized with port(s): 8080 (http)
  2. Starting service [Tomcat]
  3. Starting Servlet engine: [Apache Tomcat/9.0.19]
  4. Initializing Spring embedded WebApplicationContext
  5. Root WebApplicationContext: initialization completed in 5748 ms
  6. HikariPool-1 - Starting...
  7. HikariPool-1 - Start completed.
  8. HHH000204: Processing PersistenceUnitInfo [
  9. name: default
  10. ...]
  11. HHH000412: Hibernate Core {5.3.10.Final}
  12. HHH000206: hibernate.properties not found
  13. HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
  14. HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
  15. Initialized JPA EntityManagerFactory for persistence unit 'default'
  16. Initializing ExecutorService 'applicationTaskExecutor'
  17. spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering.
  18. Explicitly configure spring.jpa.open-in-view to disable this warning
  19. Tomcat started on port(s): 8080 (http) with context path ''
  20. Started SpringBoot2DemoApplication in 17.638 seconds (JVM running for 19.1)
  21. Hibernate:
  22. select
  23. employeeen0_.id as id1_0_0_,
  24. employeeen0_.email as email2_0_0_,
  25. employeeen0_.first_name as first_na3_0_0_,
  26. employeeen0_.last_name as last_nam4_0_0_
  27. from
  28. tbl_employees employeeen0_
  29. where
  30. employeeen0_.id=?
  31. 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 操作示例

  2. 使用 Thymeleaf 和 Hibernate 的 Spring Boot CRUD 应用程序

  3. Spring Boot 分页和排序示例

学习愉快!

下载源码