This post is about validating DB schema with older versions of Hibernate. I try to update this code with Hibernate 5.
Here is a first naive implementation:
public boolean isSchemaValid() {
// EntityManagerFactory is autowired by Spring
SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);
ServiceRegistry serviceRegistry =
sessionFactory.getSessionFactoryOptions().getServiceRegistry();
try {
new SchemaValidator().validate(
new MetadataSources(serviceRegistry).buildMetadata(),
serviceRegistry);
return true;
} catch (HibernateException ex) {
return false;
}
}
Without much surprise it doesn't work since it returns true even when the schema is not valid (the schema is different or does not exist). I guess this is because the Metadataobject passed to the new SchemaValidator.validate(...) method is not complete, e.g. does not contain the @Entitybean definitions. However I have a hard time finding out or to call this validate method properly.