似乎org.hibernate.cfg.Configuration对象可以用于通过调用validateSchema方法以编程方式执行验证。 但是,此方法需要dialect和databaseMetadata对象。 我正在使用Spring,我可以从Spring上下文中获取AnnotationSessionFactoryBean对象。到目前为止,我有以下代码:如何在Hibernate中通过注释以编程方式验证数据库模式?
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层次结构在包外不可见,所以我无法以这种方式获取连接对象,以便构建数据库元数据。我怎样才能实现这个?编辑: 我想我已经取得了一些进展。有一个SchemaValidator类。现在,该代码如下所示:
AnnotationSessionFactoryBean factory = context.getBean("&AnnotationSessionFactory");
Configuration configuration = factory.getConfiguration();
SchemaValidator validator = new SchemaValidator(configuration);
validator.validate();
Howerver,现在我收到以下错误:
org.hibernate.HibernateException:发现配置没有本地数据源 - “数据源”属性必须在LocalSessionFactoryBean的设置