感谢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(没有警告):
以上将产生一些讨厌的警告,可以忽略:
2016 年 2 月 20 日下午 2:57:16 org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator 启动
服务警告:HHH000181:没有遇到适当的连接提供程序,假设应用程序将提供连接
2016 年 2 月 20 日下午 2:57:16 org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator 启动
服务警告: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);