看起来 org.hibernate.cfg.Configuration 对象可以通过调用 validateSchema 方法以编程方式执行验证。但是,此方法需要方言和数据库元数据对象。 我正在使用 Spring,并且可以从 Spring 上下文中获取 AnnotationSessionFactoryBean 对象。到目前为止,我有以下代码:
AnnotationSessionFactoryBean factory = null;
factory = (AnnotationSessionFactoryBean) context.getBean("AnnotationSessionFactory");
Configuration configuration = factory.getConfiguration();
//the following line does not work, ConnectionHelper hierarchy is not visible outside the package
ConnectionHelper connectionHelper =
new ManagedConnectionProviderConnectionHelper(factory.getHibernateProperties());
Dialect dialect = Dialect.getDialect(factory.getHibernateProperties());
Connection connection = null;
DatabaseMetadata databaseMetadata = null;
try {
databaseMetadata = new DatabaseMetadata(connection, dialect);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
configuration.validateSchema(dialect, databaseMetadata);
我是否在正确的轨道上?ConnectionHelper层次结构在包外不可见,所以我无法通过那种方式获取连接对象,以构建databaseMetadata。我该如何实现这个呢?
编辑: 我想我已经取得了一些进展。有一个SchemaValidator类。代码现在看起来像这样:
AnnotationSessionFactoryBean factory = context.getBean("&AnnotationSessionFactory");
Configuration configuration = factory.getConfiguration();
SchemaValidator validator = new SchemaValidator(configuration);
validator.validate();
然而,现在我遇到了以下错误:
org.hibernate.HibernateException:未找到本地DataSource配置 - 'dataSource'属性必须在LocalSessionFactoryBean上设置。