Spring Boot Hibernate 配置示例

Spring Boot Hibernate 配置示例

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

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

1. Maven 依赖

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

pom.xml

<?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 APIJPA 实现(默认以 Hibernate 实现),JDBC 和其他必需的库。
  • h2:尽管我们可以使用application.properties文件中的数据源属性轻松添加任何数据库,但我们正在使用 h2 数据库来减少不必要的复杂性。

2. 创建 JPA 实体类

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

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

EmployeeEntity.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 注解

3. 创建 JPA 存储库

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

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

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

#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

#Schema will be created using schema.sql and data.sql files

spring.jpa.hibernate.ddl-auto=none

schama.sql

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

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接口进行此测试。 应用程序启动后立即执行CommandLineRunner中的run()方法。

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

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 操作示例

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

  3. Spring Boot 分页和排序示例

学习愉快!

下载源码