Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanche/d8c821e1478733576882 to your computer and use it in GitHub Desktop.
Save ivanche/d8c821e1478733576882 to your computer and use it in GitHub Desktop.
Using annotated classes in SchemaExport(Hibernate 5.1).
package ru.ivanche.clientmanager.util;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Environment;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.TargetTypeHelper;
import ru.ivanche.clientmanager.dao.Client;
import java.io.FileInputStream;
import java.util.Properties;
/**
* @author IvanChe <ivanche.freelancer@gmail.com>.
*/
public class HibernateUtil {
final static String userDir = Environment.getProperties().getProperty("user.dir");
public static void main(String[] args) {
try {
StandardServiceRegistry serviceRegistry = buildStandardServiceRegistry(args);
final MetadataImplementor metadata = buildMetadata( serviceRegistry );
final String outputFile = userDir + "/init.sql";
new SchemaExport()
.setHaltOnError( false )
.setOutputFile(outputFile)
.setFormat( true )
.execute( TargetTypeHelper.parseLegacyCommandLineOptions(true, false, outputFile),
SchemaExport.Action.BOTH, metadata, serviceRegistry );
} catch (Exception e) {
e.printStackTrace();
}
}
private static MetadataImplementor buildMetadata(StandardServiceRegistry serviceRegistry) {
final MetadataSources metadataSources = new MetadataSources( serviceRegistry );
final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
metadataSources.addAnnotatedClass(Client.class);
return (MetadataImplementor) metadataBuilder.build();
}
private static StandardServiceRegistry buildStandardServiceRegistry(String[] args)
throws Exception {
final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );
Properties properties = new Properties();
properties.load( new FileInputStream( userDir + "/src/main/resources/config/hibernate.properties") );
ssrBuilder.applySettings( properties );
return ssrBuilder.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment