While migrating from Hibernate 4 to 5 I came across the deprecation and eventual removal of the SchemaExport(Configuration) constructor. What is a good alternat
I like the diluted answer already posted. But here's a bit more detail that includes a few of the new built in Hibernate enums that allow you to create database tables with the SchemaExport class more programatically without a reliance on property file type settings like hbm2ddl.
HashMap for propertiesNormally I like to include all the database settings in Properties type of object like a Hashtable or HashMap. Then the HashMap is passed to the ServiceRegistry.
Map settings = new HashMap<>();
settings.put("connection.driver_class", "com.mysql.jdbc.Driver");
settings.put("dialect", "org.hibernate.dialect.MySQLDialect");
settings.put("hibernate.connection.url", "jdbc:mysql://localhost/hibernate_examples");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "password");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build();
MetadataSourcesThen add all your JPA annotated classes to the MetadataSources object:
MetadataSources metadata = new MetadataSources(serviceRegistry);
metadata.addAnnotatedClass(Player.class);
Action and TargetType EnumsAfter all that's done, it's time to create the SchemaExport class and call it's execute method. In doing so, you can use the TargetType.DATABASE enum and the Action.BOTH enum instead of putting hbm2ddl into the settings such as:
applySetting("hibernate.hbm2ddl.auto", "create")
Here's how it looks:
EnumSet enumSet = EnumSet.of(TargetType.DATABASE);
SchemaExport schemaExport = new SchemaExport();
schemaExport.execute(enumSet, Action.BOTH, metadata.buildMetadata());
And sorry if this gets long, but here's the whole version 5 Hibernate SchemaExport code together in one go:
Map settings = new HashMap<>();
settings.put("connection.driver_class", "com.mysql.jdbc.Driver");
settings.put("dialect", "org.hibernate.dialect.MySQLDialect");
settings.put("hibernate.connection.url", "jdbc:mysql://localhost/jpa");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "password");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.format_sql", "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build();
MetadataSources metadata = new MetadataSources(serviceRegistry);
//metadata.addAnnotatedClass(Player.class);
EnumSet enumSet = EnumSet.of(TargetType.DATABASE);
SchemaExport schemaExport = new SchemaExport();
schemaExport.execute(enumSet, Action.BOTH, metadata.buildMetadata());
The source code is available on GitHub.