1. 引言

Spring Boot 与 JPA 的无缝集成,让实现应用的数据访问层变得异常简单。其强大特性之一就是能基于 Java 实体类自动创建和管理数据库 schema。只需简单配置,就能让 Spring Boot 读取实体类并自动创建或更新数据库结构。

本文将介绍如何利用 Spring Boot 和 JPA 的能力自动生成数据库 schema,无需手写 SQL 语句。同时也会分享一些配置过程中常见的踩坑点。

2. 配置自动创建 Schema

本节将介绍配置 Spring Boot 自动创建数据库的步骤。

2.1 添加必要依赖

在配置 schema 创建前,确保项目包含正确的依赖。

首先需要 Spring Data JPA 进行数据库交互,它提供了 JPA 的抽象层:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

然后根据数据库类型添加对应依赖:

  • H2 数据库

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </dependency>
    
  • MySQL

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    
  • PostgreSQL

    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <scope>runtime</scope>
    </dependency>
    

2.2 配置 application.properties

Spring Boot 通过 application.properties 定义配置,这里需要设置数据库连接信息和其他参数。

  • H2 数据库配置

    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=password
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
    
  • MySQL 配置

    spring.datasource.url=jdbc:mysql://localhost:3306/mydb
    spring.datasource.username=root
    spring.datasource.password=password
    spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
    
  • PostgreSQL 配置

    spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
    spring.datasource.username=postgres
    spring.datasource.password=password
    spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
    

2.3 理解 spring.jpa.hibernate.ddl-auto 选项

核心配置项 spring.jpa.hibernate.ddl-auto 控制应用启动时的 schema 管理行为,可选值包括:

  • none:不生成或验证 schema(适合数据库已完全就绪的场景)
  • validate:验证现有 schema 是否匹配实体类(不修改结构,不匹配时抛异常)
  • update:更新 schema 匹配实体类(新增表/列,不删除现有结构)
  • create:每次启动时重建整个 schema(会清空数据)
  • create-drop:启动时创建 schema,关闭时删除(适合测试环境)
  • drop:仅删除 schema(不重建)

生产环境常用 update 选项,确保 schema 演进的同时避免数据丢失。

2.4 创建实体类

**配置完成后即可创建 实体类**,它们直接映射数据库表结构:

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String firstName;
    private String lastName;
    
    // getters & setters
}

关键注解说明:

  • @Entity:标记为 JPA 实体(默认映射到同名的 Person 表)
  • @Id:指定主键字段
  • @GeneratedValue:配置主键生成策略(IDENTITY 表示数据库自增)

3. 测试功能

通过 Spring Data JPA 测试保存和查询 Person 实体:

@SpringBootTest
public class PersonRepositoryTest {
    
    @Autowired
    private PersonRepository personRepository;
    
    @Test
    public void testSaveAndRetrievePerson() {
        // 确保初始无数据
        assertEquals(0, personRepository.count());
        
        // 创建并保存实体
        Person person = new Person();
        person.setFirstName("John");
        person.setLastName("Doe");
        Person savedPerson = personRepository.save(person);
        
        // 验证保存结果
        assertNotNull(savedPerson);
        assertTrue(savedPerson.getId() > 0);
        assertEquals("John", savedPerson.getFirstName());
        assertEquals("Doe", savedPerson.getLastName());
        
        // 验证数据库记录数
        assertEquals(1, personRepository.count());
    }
}

测试逻辑:

  1. 初始验证数据库无记录
  2. 创建新 Person 实体并保存
  3. 验证保存后的实体属性(ID 自增、姓名正确)
  4. 确认数据库记录数变为 1

4. 常见问题排查

自动创建 schema 通常很简单,但有时会遇到问题,这里列出几个典型踩坑点:

1. 表创建失败(命名/方言问题)
确保 spring.jpa.database-platform 正确配置数据库方言(如 MySQL 用 MySQL8Dialect)。

2. 开启 SQL 日志调试
设置 spring.jpa.show-sql=true 打印 Hibernate 生成的 SQL,便于定位问题。

3. 实体类位置错误
实体类必须位于主启动类所在包或其子包下,否则 Spring Boot 无法扫描到。

4. 配置文件位置错误
application.properties 必须放在 src/main/resources 目录。

5. 数据库连接配置错误
连接参数错误可能导致 Spring Boot 默认使用内存数据库(如 H2),检查日志确认实际连接的数据库。

6. 自定义数据源前缀问题
当使用非 spring.datasource.* 前缀(如 h2.datasource.*)时,需手动配置数据源 Bean:

@Configuration
public class DataSourceConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "h2.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
}

5. 总结

本文介绍了如何使用 Spring Boot 和 JPA 自动创建/更新数据库 schema。这个强大特性通过最小化配置,让数据库 schema 与 Java 实体保持同步,确保应用一致性并避免 schema 相关问题。合理使用 ddl-auto 选项,开发阶段能极大提升效率,生产环境则需谨慎选择策略。


原始标题:Automatically Create a Database Schema With Spring Boot | Baeldung