在 Spring Boot 中从 Hibernate 实体类生成 CREATE TABLE sql?

问题描述 投票:0回答:1

我需要在我使用 Hibernate 创建实体的 Spring Boot 应用程序中为

schema.sql
生成 CREATE TABLE sql 子句。通常我更喜欢使用
Flyway
并通过
JPA Buddy
插件生成表创建脚本。但是这次我必须使用
schema.sql
并且该插件不适用于 H2 数据库。

我的问题是:

1) 如何为

schema.sql
生成 CREATE TABLE sql 子句?

2)

H2
PostgreSQL
的表(和必要的 pk、fk、约束)创建脚本之间有什么区别吗?

java sql spring-boot hibernate database-migration
1个回答
0
投票

您可以使用

SchemaExport
课程。下面的方法展示了如何做到这一点:

public static void dumpSchema(String dialect, Class<?>... clazz) {

        Properties properties = new Properties();
        properties.put("hibernate.dialect", dialect);

        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(properties).build();

        MetadataSources metadataSource = new MetadataSources(serviceRegistry);

        Stream.of(clazz).forEach(metadataSource::addAnnotatedClass);
        Metadata meta = metadataSource.buildMetadata();

        SchemaExport schemaExport = new SchemaExport();
        schemaExport.setDelimiter(";");
        schemaExport.execute(EnumSet.of(TargetType.STDOUT), Action.CREATE, meta);
    }

用它来生成 H2 的脚本:

//list out all of your entities in the method call 

SchemaUtil.dumpSchema("org.hibernate.dialect.H2Dialect" , 
   FooEntity.class,
   BarEntity.class,
   BazEntity.class);

然后它将 CREATE TABLE 脚本转储到控制台。

表格(和必要的pk,fk, 约束)为 H2 和 PostgreSQL 创建脚本 ?

可能会有差异。毕竟他们是不同的数据库。要了解差异,您可以比较为它们生成的脚本。对于 PostgreSQL ,您必须将方言指定为

org.hibernate.dialect.PostgreSQL10Dialect

附言如果您使用的是 Hibernate 6,

SchemaExport
类将移至
hibernate-ant
模块。

© www.soinside.com 2019 - 2024. All rights reserved.