多亏了 Vlad 和 Gunnar 的回答,我设法通过新的配置 API 找到了自己的方式,以生成具有以下等效的导出逻辑。当然,历史表明这个API会再次中断,所以一定要选择合适的版本:
休眠 5.2:
MetadataSources metadata = new MetadataSources(
new StandardServiceRegistryBuilder()
.applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
.applySetting("javax.persistence.schema-generation-connection", connection)
.build());
// [...] adding annotated classes to metadata here...
metadata.addAnnotatedClass(...);
SchemaExport export = new SchemaExport();
export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
休眠 5.2(无警告):
以上将产生一些令人讨厌的警告,这些警告可以忽略:
Okt 20, 2016 2:57:16 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: 未遇到适当的连接提供程序,假设应用程序将提供连接
Okt 20, 2016 2:57:16 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: 无法获取查询元数据的连接: 应用程序必须提供 JDBC 连接
...或者您可以通过将以下内容黑客入侵到设置中来绕过它们(在我看来,这不应该是必需的)ConnectionProvider
.applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {
@Override
public boolean isUnwrappableAs(Class unwrapType) {
return false;
}
@Override
public <T> T unwrap(Class<T> unwrapType) {
return null;
}
@Override
public Connection getConnection() {
return connection; // Interesting part here
}
@Override
public void closeConnection(Connection conn) throws SQLException {}
@Override
public boolean supportsAggressiveRelease() {
return true;
}
})
休眠 5.0:
MetadataSources metadata = new MetadataSources(
new StandardServiceRegistryBuilder()
.applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
.build());
// [...] adding annotated classes to metadata here...
metadata.addAnnotatedClass(...);
SchemaExport export = new SchemaExport(
(MetadataImplementor) metadata.buildMetadata(),
connection // pre-configured Connection here
);
export.create(true, true);
休眠 4:
提醒一下,这是在Hibernate 4中的工作原理:
Configuration configuration = new Configuration()
.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
// [...] adding annotated classes to metadata here...
configuration.addAnnotatedClass(...);
configuration.generateSchemaCreationScript(
Dialect.getDialect(configuration.getProperties()));
SchemaExport export = new SchemaExport(configuration, connection);
export.create(true, true);