通过调用validateSchema方法,似乎可以将org.hibernate.cfg.Configuration对象用于以编程方式执行验证。但是,此方法需要方言和databaseMetadata对象。我正在使用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:找不到用于配置的本地数据源- 必须在LocalSessionFactoryBean上设置’dataSource’属性
最后,使用Spring并不是那么简单。我设法做到了扩展AnnotationSessionFactoryBean像这样:
public class SchemaValidatingAnnotationSessionFactoryBean extends AnnotationSessionFactoryBean { public void validateDatabaseSchema() throws DataAccessException { logger.info("Validating database schema for Hibernate SessionFactory"); HibernateTemplate hibernateTemplate = new HibernateTemplate( getSessionFactory()); hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); hibernateTemplate.execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Connection con = session.connection(); Dialect dialect = Dialect.getDialect(getConfiguration() .getProperties()); DatabaseMetadata metadata = new DatabaseMetadata(con, dialect); Configuration configuration = getConfiguration(); configuration.validateSchema(dialect, metadata); return null; } }); } }