views:

39

answers:

2

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?

+1  A: 

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)

Arthur Ronald F D Garcia
Arthur, Thanks a lot for your valuable input.
Vanathi
+1  A: 

I've always used Hibernate this way. As long as whatever API you're using can interact with it in a sensible way (and most can), I see no reason to do all that work yourself when Hibernate can do it for you.

That's the nice thing about frameworks like Hibernate. They save you lots of time, they're usually well documented, and everything else is designed to "play nice" with them. All you have to do is trust them :)

Dan M
Dan, Thanks a lot for your thoughts.
Vanathi