Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to let Hibernate create the tables automatically using <property name="hbm2ddl.auto">create</property>?

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?

like image 805
Vaandu Avatar asked Sep 21 '10 03:09

Vaandu


1 Answers

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)

like image 108
Arthur Ronald Avatar answered Oct 17 '22 18:10

Arthur Ronald