如何使用Hibernate 5在没有数据库连接的情况下创建SQL文件

3
在Hibernate 4中,我使用config.generateSchemaCreationScript(dialect);从我们的类生成SQL创建脚本文件。在升级到Hibernate 5(确切地说是5.6.5.Final)后,我正在尝试创建相同的行为。
尝试了以下方法:
Configuration config = new Configuration();
for (Class<?> type : types) {
  config.addAnnotatedClass(type);
}
ServiceRegistry serviceRegistry = config.getStandardServiceRegistryBuilder().applySetting(Environment.DIALECT, MariaDBDialect.class).build();
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();

SchemaExport schemaExport = new SchemaExport();
schemaExport.setHaltOnError(true);
schemaExport.setFormat(true);
schemaExport.setDelimiter(";");
schemaExport.setOutputFile(new File("create.sql"));
schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata);

这段代码给我带来了很多警告 "java.sql.SQLException: No suitable driver" 和 "java.sql.SQLException: Connections could not be acquired from the underlying database!"。看起来创建元数据对象时已经尝试创建数据库连接。但是我没有/不想要数据库连接,我只想从数据库对象创建SQL文件。

我也尝试过执行 schemaExport.execute(EnumSet.of(TargetType.SCRIPT), Action.CREATE, null, serviceRegistry);。这仍然会尝试设置数据库连接,并在元数据的空指针异常上失败。

如何在Hibernate 5中从我的配置中创建SQL文件而不需要数据库连接?

1个回答

3

我也遇到了同样的问题,但无法找到阻止它发生的方法。作为一个解决方法,我使用了hsqldb:读取hibernate.properties文件并仅修改驱动程序/URL/用户名/密码以适应hsqldb,然后将属性传递给hibernate进行处理:这样hibernate就可以连接到一个数据库(即使它不需要这个任务),同时方言保持不变,这对于DDL/sql脚本生成非常重要;经过测试证明有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接