How to validate database schema programmatically in hibernate with annotations?

断了今生、忘了曾经 提交于 2019-11-29 04:52:06

In the end, when using Spring this is not that simple. I managed to do it extending the AnnotationSessionFactoryBean like this:

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;
        }
    });

}
}

I have found a simpler solution for invoking hibernate mapping validation that works for me : LocalSessionFactoryBean.validateDatabaseSchema() (which effectively does the same thing as the code in Dan's answer above)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/some-test-context.xml" })
public class TestMapping {

    @Autowired
    ApplicationContext context; 

    @Test
    public void validateSchema() {
        AnnotationSessionFactoryBean factory = (AnnotationSessionFactoryBean)context
                .getBean("&mySessionFactory");
        factory.validateDatabaseSchema(); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!