Reputation: 83
I'm using JPA persistence in a Java web project, which runs on Wildfly 11. It's using Hibernate 5.1. Sometimes the database schema changes and I try to be very careful to change the production databases in the same way as I change my Java code for the entities.
However, I need to be able to run update scripts before the application boots up. After those ran, the database should be in the right state.
So I added a bean with @Singleton
and @Startup
. That bean takes care of updating the schema nicely. It detects the current database version and selects the right update scripts.
Since I'm modifying the Java code of the entities by hand and doing the update scripts by hand, I'd like to have a way to validate my work. I know I can activate hibernate.hbm2ddl.auto
and set it to validate
. But then my update scripts wouldn't work, since in that case, validation takes place before the schema is updated. So ideally I'd like to run validation manually inside that class, after all updates are through.
I tried to use org.hibernate.tool.hbm2ddl.SchemaValidator
, but I need an instance of org.hibernate.boot.Metadata
and I failed to get it out of my EntityManager
. So if someone could tell me how to get that, that would possibly solve this problem. I was able to get a org.hibernate.service.ServiceRegistry
.
I also tried to add another persistence unit, one without validation and one with hibernate.hbm2ddl.auto
set to validate
, but it turned out, that this setting is global and either all units will have validation enabled or none. Maybe I was doing it wrong, but I see it as an undesirable solution anyway. But still, better than nothing.
Maybe there is also some library I can use to validate the database schema. I had a look at Liquibase, but it seemed to take control of everything and not validate the JPA against the database.
Maybe my whole approach to developing this kind of application is not ideal, but I figured, that I really need control over my database and also over the entities.
Any hints are welcome! Thanks in advance.
Upvotes: 2
Views: 531