I am trying to write a Liquibase changeset generator based on SchemaUpdate class provided by Hibernate. The goal is to have the benefits of Hibernate update scripts and the possibility for developpers to tweak them as needed. When done, the SQL will be intergated in a Liquibase SQL file.
This seemed very simple at the beginning, by instanciating a SchemaUpdate class and launch the execute method.
But the code does anything. I am trying to initialize Hibernate from a JPA persistence.xml file and I think that's the problem.
For the moment I have manually set mysql properties, but Hibernate doesn't find the entity classes.
What's the best way to get a configuration (needed by the SchemaUpdate class) from JPA configuration ?
I've searched a solution for a while now, but all of them use EJB3Configuration class which doesn't exist anymore in Hibernate 4.3.
Thaks for Help !
For example, I am doing something like this :
final File persistenceFile = new File("src/main/resources/META-INF/persistence.xml");
final Configuration cfg = new Configuration();
if ( ! persistenceFile.exists()) {
throw new FileNotFoundException(persistenceFile.getAbsolutePath() + " not found");
}
final List<String> jpaConfiguration = Files.readLines(persistenceFile, Charsets.UTF_8);
for (final String line : jpaConfiguration) {
if (line.contains("property")) {
final String[] props = line.split("\\\"");
cfg.setProperty(props[1], props[3]);
}
}
final SchemaUpdate updater = new SchemaUpdate(cfg);
updater.setOutputFile("target/script.sql");
updater.execute(true, false);
This solution has a drawback. You must also include the 'package-info.java', if there is one. There is a simpler solution (at least for now).
HibernatePersistenceProvider can generate EntityManagerFactoryBuilder and EntityManagerFactoryBuilderImpl has a function to give a Configuration back. Unfortunately, this function is protected, so must HibernatePersistenceProvider be derived.
private class MyHibernatePersistence extends HibernatePersistenceProvider {
@Override
public EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String persistenceUnitName, Map properties) {
return super.getEntityManagerFactoryBuilderOrNull(persistenceUnitName, properties);
}
}
This can be easily created a Configuration, which takes into account all the data, which are also used for a EntityManager.
public Configuration getConfiguration(String persistenceUnitName, Map<String, Object> properties) {
MyHibernatePersistence hpp = new MyHibernatePersistence();
EntityManagerFactoryBuilder emfb = hpp.getEntityManagerFactoryBuilderOrNull(persistenceUnitName, properties));
if (emfb instanceof EntityManagerFactoryBuilderImpl) {
emfb.build();
return ((EntityManagerFactoryBuilderImpl) emfb).getHibernateConfiguration();
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With