How to get access to database table metadata with Hibernate 5

Introduction

One of my readers has recently asked me to answer this StackOverflow question, and because the question is very interesting, I decided to turn the answer into a blog post.

In this article, I’m going to show you how you can get access to database table metadata using Hibernate 5 API.

Integrator

Hibernate is very flexible, so it defines many SPI (Service Provider Interfaces) that you can register to customize Hibernate internals. One of these interfaces is org.hibernate.integrator.spi.Integrator which is used by many technologies that integrate with Hibernate ORM, like Bean Validation, Envers or JACC Security Provider.

Using the Hibernate Integrator API, we can write our own component that captures the SessionFactory build-time metadata which, otherwise, is only available during bootstrap.

Try via the hibernate.integrator_provider configuration property. If that does not work, you need to inspect the Spring codebase and see how you can extend it or add support for setting the Integrator and send them a Pull Request.

Thank you for an interesting article. I am using Spring LocalContainerEntityManagerFactoryBean and among other things, a lot of hibernate.* properties are being set in a HashMap with its setJpaPropertyMap method. I tried adding MetadataExtractorIntegrator.INSTANCE as the hibernate.integrator_provider property like you do above in the JPA bootstrap configuration. Yet the Database member variable stays null. How would you go about integrating MetadataExtractorIntegrator with LocalContainerEntityManagerFactoryBean? Any other ideas on getting database metadata when using Spring and JPA/Hibernate?

Actually, it’s very easy. Just use the getJPAPropertyMap and pass the Integrator from a Java-based config. It’s much easier to do it using Java configurations rather than using XML (although it’s probably doable via XML too as long as the Integrator is passed as a bean)