I know that adding "hbm2ddl.auto"=create Hibernate will create the tables automatically reading the mapping from the hbm / the annotation. Please let me know that if this is a good practice to follow and why?
If you use it in a test environment (if possible, by using a in-memory database such as h2 - yes, it is just a singe jar file), it can be a good idea (make sure you do not have any production related settings)
An advice retrieved from Hibernate In Action book which can also be applied is
We have seen Hibernate users trying to use SchemaUpdate to update the schema of a production database automatically. This can quickly end in disaster and will not be allowed by your DBA.
If you just want to generate the schema, prefer to use SchemaExport (The class behind the scenes of hbm2ddl)
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration
.addAnnotatedClass(<TYPE_YOUR_CLASS>.class)
.setProperty(Environment.USER, <TYPE_YOUR_USER>)
.setProperty(Environment.PASS, <TYPE_YOUR_PASSWORD>)
.setProperty(Environment.URL, <TYPE_YOUR_URL>)
.setProperty(Environment.DIALECT, <TYPE_YOUR_DIALECT>)
.setProperty(Environment.DRIVER, <TYPE_YOUR_DRIVER>);
SchemaExport schema = new SchemaExport(configuration);
schema.setOutputFile("schema.sql");
schema.create(<DO_YOU_WANT_TO_PRINT_TO_THE_CONSOLE>, <DO_YOU_WANT_TO_EXPORT_THE_SCRIPT_TO_THE_DATABASE>);
You can also enable Java properties according to target machine
-Dprofile=development
or
-Dprofile=production
An approach is shown here (Although it uses Spring, Spring has built-in support for Hibernate)
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